如何 select 来自一个 table 的数据在另一个 table 中没有任何价值
How to select data from one table that doesn't have any value from another table
我的查询有问题(使用 SQL Developer)。这可能是一个简单的案例,但我的想法有问题......所以我有两个表 GROUP 和 PERSON。我需要 select 所有没有男性的组。所以在这种情况下 SQL 对我来说应该 return 只有 GROUP_NAME 的狗 (GROUP_ID = 2) 因为它们只有雌性。我感谢所有的帮助!
所以表 1 组:
和表 2 人:
尝试
SELECT
GROUP_NAME
FROM GROUP_TABLE g
WHERE NOT EXISTS
(SELECT 1 FROM PERSON p WHERE SEX = 'male' AND p.GROUP_ID = g.GROUP_ID)
SELECT G.GROUP_ID,G.GROUP_NAME
FROM GROUP G
WHERE NOT EXISTS
(
SELECT 1 FROM PERSON P WHERE G.GROUP_ID=P.GROUP_ID AND P.SEX='MALE'
)
select a.group_id
from group a, person b
where a.group_id=b.group_id and
group by a.group_id having COUNT(CASE b.sex WHEN 'male' THEN 1 END)=0 and
COUNT(CASE b.sex WHEN 'female' THEN 1 END)>0
要查找没有男性的组,您可以使用 OUTER JOIN
从组中仅找到男性,然后找到没有匹配项的组:
SELECT g.*
FROM "GROUP" g
LEFT OUTER JOIN person p
ON (p.group_id = g.group_id AND p.sex = 'Male')
WHERE p.group_id IS NULL;
如果你想在至少有一个女性而没有男性的情况下找到组,那么你可以使用:
SELECT *
FROM "GROUP" g
WHERE EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
AND sex = 'Female'
)
AND NOT EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
AND sex = 'Male'
)
或者:
SELECT *
FROM "GROUP" g
WHERE EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
HAVING COUNT(CASE sex WHEN 'Female' THEN 1 END) > 0
AND COUNT(CASE sex WHEN 'Male' THEN 1 END) = 0
)
我的查询有问题(使用 SQL Developer)。这可能是一个简单的案例,但我的想法有问题......所以我有两个表 GROUP 和 PERSON。我需要 select 所有没有男性的组。所以在这种情况下 SQL 对我来说应该 return 只有 GROUP_NAME 的狗 (GROUP_ID = 2) 因为它们只有雌性。我感谢所有的帮助!
所以表 1 组:
和表 2 人:
尝试
SELECT
GROUP_NAME
FROM GROUP_TABLE g
WHERE NOT EXISTS
(SELECT 1 FROM PERSON p WHERE SEX = 'male' AND p.GROUP_ID = g.GROUP_ID)
SELECT G.GROUP_ID,G.GROUP_NAME
FROM GROUP G
WHERE NOT EXISTS
(
SELECT 1 FROM PERSON P WHERE G.GROUP_ID=P.GROUP_ID AND P.SEX='MALE'
)
select a.group_id
from group a, person b
where a.group_id=b.group_id and
group by a.group_id having COUNT(CASE b.sex WHEN 'male' THEN 1 END)=0 and
COUNT(CASE b.sex WHEN 'female' THEN 1 END)>0
要查找没有男性的组,您可以使用 OUTER JOIN
从组中仅找到男性,然后找到没有匹配项的组:
SELECT g.*
FROM "GROUP" g
LEFT OUTER JOIN person p
ON (p.group_id = g.group_id AND p.sex = 'Male')
WHERE p.group_id IS NULL;
如果你想在至少有一个女性而没有男性的情况下找到组,那么你可以使用:
SELECT *
FROM "GROUP" g
WHERE EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
AND sex = 'Female'
)
AND NOT EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
AND sex = 'Male'
)
或者:
SELECT *
FROM "GROUP" g
WHERE EXISTS(
SELECT 1
FROM person p
WHERE p.group_id = g.group_id
HAVING COUNT(CASE sex WHEN 'Female' THEN 1 END) > 0
AND COUNT(CASE sex WHEN 'Male' THEN 1 END) = 0
)