我有两个使用查询创建的表:
create table person (SSN int, name varchar(50));
create table accountInfo (SSN int, accNo int, bank varchar(50));
insert into person values (123, "Alfred"), (467, "Bond"),(896, "Charly"), (563, "Debora");
insert into accountInfo values (123, 1111,"BoA");
insert into accountInfo values (467, 1222,"BoA");
insert into accountInfo values (123, 333,"Chase");
insert into accountInfo values (896, 444,"Chase");
insert into accountInfo values (123, 555,"USB");
insert into accountInfo values (467, 666,"USB");
我的问题是计算accountInfo
除以person
的正确查询是什么。我试过使用这个查询,但它并没有很好地运作。
SELECT DISTINCT accountInfo.bank AS bank FROM accountInfo accountInfo1
WHERE NOT EXISTS
(SELECT person.SSN FROM person
WHERE person.SSN NOT IN (SELECT accountInfo2.SSN FROM accountInfo accountInfo2 WHERE accountInfo2.bank = accountInfo1.bank));
结果应为
+------+
| SSN |
+------+
| 123 |
+------+
答案 0 :(得分:1)
尝试使用HAVING
子句:
SELECT p.SSN, COUNT(DISTINCT a.bank) AS bankCount
FROM person p
JOIN accountInfo a ON a.SSN = p.SSN
GROUP BY p.SSN
HAVING bankCount = (SELECT COUNT(DISTINCT bank) FROM accountInfo);