0

我有一个查询

SELECT * FROM my_tbl1
WHERE id IN ( SELECT id1 FROM my_tbl2 WHERE user_id=2)
OR    id IN ( SELECT id2 FROM my_tbl2 WHERE user_id=2)
OR    id IN ( SELECT id3 FROM my_tbl2 WHERE user_id=2)
OR    id IN ( SELECT id4 FROM my_tbl2 WHERE user_id=2)
OR    id IN ( SELECT id5 FROM my_tbl2 WHERE user_id=2)

.......
OR    id IN ( SELECT id22 FROM my_tbl2 WHERE user_id=2)

id1id2等等id22my_tbl2中的列。这让我写了 22 次OR子句并一次又一次地点击 my_tbl2 。

我试过GROUP_CONCAT但那个只返回由逗号分隔的字符串。所以这不起作用

我的意思是下面的查询没有帮助

 SELECT * FROM my_tbl1
    WHERE id IN ( SELECT GROUP_CONCAT(id1,id2,id3..id22) FROM my_tbl2 WHERE user_id=2)

另一个想法,我担心IN CLAUSE的子查询

   SELECT * FROM my_tbl1 a 
        WHERE EXISTS ( SELECT 1 FROM my_tbl2 b 
    WHERE b.user_id=2 AND a.id IN (b.id1,b.id2,b.id3...b.id22 )

有什么办法可以简化这个吗?

谢谢你

4

2 回答 2

1
select my_tbl1.* from my_tbl1,my_tbl2
where (id=id1 or id=i2 ... or id=id22) and user_id=2
于 2013-09-17T08:27:56.387 回答
0

如何使用FIND_IN_SET()

WHERE FIND_IN_SET(ID, (SELECT CONCAT_WS(',',id1,id2,id3,...,id22)  
                       FROM my_tbl2 
                       WHERE user_id=2)) > 0

或使用JOININ

SELECT  DISTINCT a.*
FROM    my_tbl1 a
        INNER JOIN my_tbl2 b
            ON a.id IN (b.id1,b.id2,b.id3,...,b.id22)
WHERE   b.user_id = 2
于 2013-09-17T08:36:03.170 回答