检查两个表之间的数据

时间:2011-10-28 09:22:15

标签: mysql sql database

我想检查表1中是否存在OrderID = 2,而表2中是否存在,则返回1或为真。

如果两个表中都存在OrderID = 2,则返回0或false ..

如何在SQL查询中完成?

Table1
=======
ID | OrderID
1    2
2    2

Table2
======
OrderID | Name
1         A
2         B

3 个答案:

答案 0 :(得分:1)

那样的东西?

select ID,t1.OrderID, t2.OrderID is null as notinboth
from table1 as t1 left join table2 as t2 using (OrderID);

答案 1 :(得分:0)

SELECT ID FROM Table1 INNER JOIN Table2 ON Table2.OrderID = Table1.OrderID

您将获得ID或null

答案 2 :(得分:-1)

select 
    case when 
        exists (select * from table1 where orderid = 2) and 
        exists (select * from table2 where orderid = 2) 
    then 0 
    else 1 
    end