0

Do you know how to translate a SQL query with a subquery in a FROM clause ?

Here is an example :

SELECT 
    *
FROM
    cars
WHERE
    cars.id IN (
    SELECT
        cars.user_id
    FROM 
        cars AS cf, (SELECT
        cars.user_id, MAX(consumption) AS consumption FROM
        cars
    GROUP BY
        user_id) AS t1
    WHERE
        cars.consumption = t1.consumption
        AND
        cars.user_id = 2
        AND
        t1.user_id = cars.user_id)
1
  • I have a feeling you're overcomplicating things here. Can you provide an example data set and an example result set from that data that you're trying to select? Commented Jan 6, 2020 at 13:09

1 Answer 1

1
Car.where('id IN (SELECT cars.user_id FROM cars AS cf, (SELECT cars.user_id, MAX(consumption) AS consumption FROM cars GROUP BY user_id) AS t1 WHERE cars.consumption = t1.consumption AND cars.user_id = :user_id AND t1.user_id = cars.user_id)', user_id: 2)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, why complicate things when they can be simple?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.