gpt4 book ai didi

mysql - 在第一个查询中使用所选列并在第二个查询中使用 IN 子句

转载 作者:行者123 更新时间:2023-11-29 10:09:05 25 4
gpt4 key购买 nike

问题已重现如下:

/* query - 1 */
Select id, title from table1;

/* returns */

id | title
-----------
1 | data-1
2 | data-2
3 | data-3
4 | data-4
5 | data-5

我想在第二个查询中使用此列 ID 的数据和 IN 子句以及连接。像这样的事情:

Select id, title from table1
JOIN
Select anotherColumn from table2 where table2.id IN (1,2,3,4,5) on table1.id = table2.id

如何在第二个查询中使用从第一个查询中选择的列数据,而不是手动编写1,2,3,4,5

编辑:

实际查询:

SELECT *
FROM
(
SELECT R.id, U.ic_id as rider, U.name, DP.department_name, R.location,
(R.distance - 1) + 10 as cost , R.timestamp, R.status
FROM requests AS R, iconnect.users AS U, iconnect.departments AS DP
WHERE R.pool = '125' AND R.rider = U.ic_id AND U.department = DP.id
) requestDetails
JOIN
(
SELECT AVG(rider_rating) AS rider_rating,rider
FROM
(
SELECT rider_rating, R.rider
FROM journeys AS J, requests AS R
WHERE J.req_id = R.id AND R.rider IN (12,13) LIMIT 999999
) AS allRatings
GROUP BY rider
) ratingsTable
ON requestDetails.rider = ratingsTable.rider

/* instead of (12,13) I want to use requestDetails.rider selected from the first derived table */

最佳答案

一种选择是使用 EXISTS 子句:

SELECT id, title
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2 WHERE t1.id = t2.id);

实际上,两个表之间的普通内部联接也可以工作。但是,如果 table1 中的给定记录可能与 table2 中的多个记录匹配,您可能需要使用 SELECT DISTINCT。这会给我们留下这样的结果:

SELECT DISTINCT t1.id, t1.title
FROM table1 t1
INNER JOIN table2 t2
ON t1.id = t2.id;

关于mysql - 在第一个查询中使用所选列并在第二个查询中使用 IN 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com