我有2张桌子
Table 1 ID Status 1 D 2 F 3 D Table 2 SID ID Approve 1 1 N 2 1 Y 3 1 Y 4 2 Y 5 3 Y Result:- Should be Table 1 (ID, Status) 3, D 2,F
不应显示1(其中一个子行在批准列中有N)
我需要一个查询来连接ID上的2个表,并查找其Approve列中没有N的记录。有没有人知道如何实现这个?
我试过
SELECT * FROM Table1 AS t1 INNER JOIN Table2 AS t2 ON t2.id = t1.id WHERE t2.Approve != 'N'
不起作用
答案 0 :(得分:3)
SELECT *
FROM Table1 t1
WHERE NOT EXISTS(SELECT * FROM Table2 t2 WHERE t2.ID = t1.ID AND t2.Approve = 'N')
答案 1 :(得分:1)
更高效,更容易阅读如下:
SELECT * FROM Table1 AS t1
LEFT JOIN Table2 AS t2
ON t2.id = t1.id
group by t1.id HAVING sum(t2.approve='Y') = count(t1.id)
答案 2 :(得分:0)
请尝试
SELECT distinct t1.*
FROM Table1 AS t1
INNER JOIN Table2 AS tyes
ON tyes.id = t1.id
AND tyes.approve ='Y'
LEFT OUTER JOIN Table2 as tno
ON tno.id = t1.id
AND tno.approve ='N'
where tno.sid is null
它将选择任何明确批准且永不拒绝的行
答案 3 :(得分:0)
Select * from table1 where id not in (select id from table2 where approve = 'N')
答案 4 :(得分:0)
仍然返回ID 1,因为表2中还有一条记录,其中对于ID 1,approve ='Y'。 如果要排除任何SID批准为“N”的ID,则必须使用子查询;大致是:
SELECT t1.ID,T1.Status FROM Table1 AS t1 INNER JOIN Table2 AS t2 ON t2.id = t1.id
where t1.id NOT IN (select id from Table2 where approve = 'N' and id = t1.id)
的问候,
斯泰恩