如何查找符合所有这些条件的行

时间:2013-10-02 05:34:58

标签: mysql select join rows multiple-columns

我有两张桌子:

首先:table_a

id | orderid
1    123
2    456
...

第二名:table_b

orderid | status | date
123       2        1380566559
123       4        1380566561
123       6        1380566563

我想只在orderid的状态为2且在我的表中没有状态4和6时才从table_a返回orderid行...

我尝试没有成功:(

SELECT DISTINCT(a.orderid) 
FROM table_a AS a 
INNER JOIN table_b AS b 
INNER JOIN table_b AS c 
INNER JOIN table_b AS d 
ON a.orderid = b.orderid 
WHERE b.status = 2 AND
c.status != 4 AND
d.status != 6;

3 个答案:

答案 0 :(得分:1)

SELECT a.orderid
FROM table_a AS a 
INNER JOIN table_b AS b on a.orderid = b.orderid
group by a.orderid
having sum(b.status = 2) >= 1
and sum(b.status in (4,6)) = 0

SQLFiddle demo

答案 1 :(得分:-1)

您可以在查询下方运行以获取输出。

select 
    order_id 
from table_a a 
    inner join table_b b 
        on a.order_id = b.order_id 
where b.status=2;

答案 2 :(得分:-1)

请尝试以下查询

SELECT DISTINCT(a.orderid)
FROM table_a a, table_b b
WHERE a.orderid = b.orderid
      AND b.status = 2
      AND b.status != 4
      AND b.status !=6

您可以使用以下链接进行验证 http://sqlfiddle.com/#!2/a9b89/5/0