0

我有两张桌子:

第一个: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;
4

3 回答 3

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 演示

于 2013-10-02T05:36:28.010 回答
-1

您可以在查询下运行以获取输出吗?

select 
    order_id 
from table_a a 
    inner join table_b b 
        on a.order_id = b.order_id 
where b.status=2;
于 2013-10-02T05:38:27.657 回答
-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

于 2013-10-02T05:58:23.670 回答