带有子查询的MySQL SELECT IN

时间:2012-08-01 06:03:44

标签: mysql

好吧,所以我遇到了以下问题..我正在尝试使用两个子查询执行单个select语句。我需要它做的几乎是以下......

SELECT * FROM messages WHERE满足以下条件。

条件1:

 SELECT id 
 FROM messages 
 WHERE `receiver` = 123510 && sender= 123457 && status != 3;

条件2:

 SELECT id 
 FROM messages 
 WHERE receiver = 123457 && sender = 123510 && status !=4;

我尝试了以下操作:

SELECT * 
FROM messages 
WHERE id IN (
                 (
                     SELECT id 
                     FROM messages 
                     WHERE `receiver` = 123510 && sender= 123457 && status != 3
                 ),
                 (
                     SELECT id 
                     FROM messages 
                     WHERE receiver = 123457 && sender = 123510 && status !=4)
                  )  

但是当我这样做时,mysql会回来,Subquery会返回多行...

有关如何解决此问题的任何建议?

2 个答案:

答案 0 :(得分:3)

我认为这就是你要找的东西:

SELECT *
FROM messages
WHERE (receiver = 123510 AND sender = 123457 AND status <> 3) OR
      (receiver = 123457 AND sender = 123510 AND status <> 4);

答案 1 :(得分:0)

您必须将每个查询与一个联合分开,或者将它作为两个用OR分隔的独立IN。

SELECT * 
FROM messages 
WHERE id IN (
          SELECT id
          FROM messages
          WHERE `receiver` = 123510 and 
                sender= 123457 and 
                status != 3) or
          UNION
          SELECT id
          FROM messages 
          WHERE receiver = 123457 and 
          sender = 123510 and
          status !=4)

但实际上,这样做会好得多。

SELECT * 
FROM messages 
WHERE (`receiver` = 123510 and 
       sender = 123457 and 
       status != 3) or
      (receiver = 123457 and 
       sender = 123510 and
       status !=4)