简体   繁体   中英

How to write a simple sql query using Objection.js

I need to write this mysql query with Objection.js but i can't figure it out how to properly write it.

Here's the query (1276 is an example of an id in people table):

SELECT MAX(c1.price) AS price 
FROM computers c1 
WHERE c1.ownerId = 1276 AND NOT EXISTS (
  SELECT c2.screenSize 
  FROM computers c2 
  WHERE c2.ownerId = 1276 AND c2.screenSize > c1.screenSize
  )

I have already fetched an instance of person, now i want to do something like:

person.$relatedQuery("computers", db)
  .select(db.max(db.ref("price")))
  .whereNotExists(qb => qb.where(....

Any suggestion would be really appreciated!

Because you are searching for the max price where there does not exists as screenSize that is larger, you are basically searching for the max price of the computer with the max screenSize.

If this is correct, your SQL query can be simplified/changed to:

SELECT MAX(c1.price) AS price 
FROM computers c1 
WHERE c1.ownerId = 1276 
  AND c1.screenSize= ( SELECT MAX(c2.screenSize)
                       FROM computers c2 
                       WHERE c2.ownerId = 1276 
                     )

With this your sub-query look almost the same as the outer query, which should make converting it easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM