这纯粹是一个效率问题。我有两张桌子:
根据用户ID在实体中的位置存储用户ID的方法
id | supervisor | manager | worker
-------+----------------+--------------+---------------
1 | 12 | 15 | 32
2 | 12 | 42 | 22
带有用户信息的那个:
id | name | email
-------+----------------+---------------------
12 | Bob | bob@example.com
15 | Dave | dave@example.com
是否可以仅使用一个IN
子句而不是3来执行此操作?
SELECT `name`, `email`
FROM `tbl_users`
WHERE `id` IN
(SELECT `supervisor` FROM `tbl_warehouse` WHERE `id` = 'WAREHOUSEID')
OR `id` IN
(SELECT `manager` FROM `tbl_warehouse` WHERE `id` = 'WAREHOUSEID')
OR `id` IN
(SELECT `worker` FROM `tbl_warehouse` WHERE `id` = 'WAREHOUSEID')
我尝试了一些尝试将supervisor
,manager
,worker
列合并到一列中的内容,以便IN
子句可以正常工作但是没有成功
答案 0 :(得分:1)
您可以使用EXISTS
并使用子查询中的IN
:
select `name`,
`email`
from `tbl_users` u
where exists (
select 1
from `tbl_warehouse` w
where w.id = 'WAREHOUSEID'
and u.id in (w.supervisor, w.manager, w.worker)
)
您也可以使用JOIN
实现此目的:
select u.name, u.email
from tbl_users u
join tbl_warehouse w on u.id in (w.supervisor, w.manager, w.worker)
where w.id = 'WAREHOUSEID'
答案 1 :(得分:0)
或者,还有:
SELECT
name
, email
FROM tbl_users u
JOIN (
SELECT supervisor FROM tbl_warehouse WHERE id = 'WAREHOUSEID'
UNION ALL SELECT manager FROM tbl_warehouse WHERE id = 'WAREHOUSEID'
UNION ALL SELECT worker FROM tbl_warehouse WHERE id = 'WAREHOUSEID'
) w(id)
USING(id);
并且如前所述,确保您使用INTEGER加入INTEGER ......