英文:
How to use ActiveRecord for a sql query with subquery in FROM clause
问题
你知道如何翻译带有FROM子查询的SQL查询吗?
以下是一个示例:
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)
英文:
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
得分: 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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论