问题已在下面重新创建:
/* 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 */
答案 0 :(得分:1)
一种选择是使用EXISTS
子句:
SELECT id, title
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2 WHERE t1.id = t2.id);
实际上,两个表之间的普通内部联接也将起作用。但是,如果SELECT DISTINCT
中的给定记录可以匹配table1
中的多个记录,则可能要使用table2
。这将使我们拥有:
SELECT DISTINCT t1.id, t1.title
FROM table1 t1
INNER JOIN table2 t2
ON t1.id = t2.id;