在第一个查询中使用selected列,在第二个查询中使用in子句

jjjwad0x  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(604)

已在下面重新创建问题:

/* 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的数据with in子句以及join。像这样:

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 */
dauxcl2d

dauxcl2d1#

一种选择是使用 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;

相关问题