使用join代替这两个单独的查询

时间:2011-08-25 10:41:06

标签: mysql

我有一个由以下结构和记录组成的表,我想要的只是提取那些uid为0或2的记录的list_name,但我还想检查一个记录是否可用于uid 0和2,那么只有它应该只显示uid 2的记录...我已经设法用两个查询做到了...我可以为此写一个查询......

**id**    **uid**     **list_name**
1            2        favourite list
2            0        Things i love
3            0        my list 
4            2        my lists
5            3        test334
6            2        Things i love

任何帮助或建议都将受到高度赞赏..谢谢提前..

2 个答案:

答案 0 :(得分:1)

猜猜......

SELECT
    list_name
FROM
    myTable T1
WHERE
   uid IN (0, 2)
   AND
   NOT EXISTS (SELECT * FROM myTable T2 WHERE T2.uid = 0)
UNION ALL
SELECT
   list_name
FROM
   myTable T1
WHERE
   uid = 2
   AND
   EXISTS (SELECT * FROM myTable T2 WHERE T2.uid = 0)

答案 1 :(得分:1)

另一个猜测:

SELECT
    uid, list_name
FROM
    myTable T1
WHERE
   uid = 2
   OR
   ( uid = 0 
     AND NOT EXISTS
             ( SELECT * 
               FROM myTable T2 
               WHERE T2.uid = 2
                 AND T2.list_name = T1.list_name
             )
   )