将3个单独的列组合成一个,以便在IN子句中使用

时间:2017-03-22 15:47:05

标签: mysql sql mysqli

这纯粹是一个效率问题。我有两张桌子:

根据用户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')

我尝试了一些尝试将supervisormanagerworker列合并到一列中的内容,以便IN子句可以正常工作但是没有成功

2 个答案:

答案 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 ......