我想使用SELECT
参数作为第一个查询输出进行多个WHERE
查询
SELECT id FROM hotel where group_id != 1;
输出:1,3,4,5,6,7,9
现在,我想获取这些ID(第一个查询的输出)并对其进行多个SELECT
SELECT user_id FROM users where hotel_id = [1,3,4,5,6,7,9];
答案 0 :(得分:-1)
您可以使用IN
(带有子查询)而不是=
使用以下解决方案:
-- ignore hotel_id with NULL using IN with sub-select
SELECT user_id
FROM users
WHERE hotel_id IN (
SELECT id
FROM hotel
WHERE group_id <> 1
);
-- with hotel_id NULL using IN with sub-select
SELECT user_id
FROM users
WHERE hotel_id IN (
SELECT id
FROM hotel
WHERE group_id <> 1
) OR hotel_id IS NULL;
另一个解决方案可以是使用INNER JOIN
或LEFT JOIN
的以下解决方案:
-- ignore hotel_id with NULL using INNER JOIN
SELECT users.user_id
FROM users INNER JOIN hotel ON users.hotel_id = hotel.id
WHERE hotel.group_id <> 1
-- with hotel_id NULL using LEFT JOIN
SELECT users.user_id
FROM users LEFT JOIN hotel ON users.hotel_id = hotel.id
WHERE hotel.group_id <> 1 OR users.hotel_id IS NULL;