如何选择没有特定条目的条目?

时间:2017-09-01 11:53:54

标签: mysql sql sql-server select

我有两个这样的SQL表:

T1

Animal   Name
Cat      Paul
Cat      Miau
Cat      Paul
Cat      Peter

T2

Legs   Name
4      Paul
4      Miau
3      Paul
4      Peter

我想要的是这样一个表:

Animal   Legs   Name
Cat       4     Miau
Cat       4     Peter

我希望所有动物都有特定数量的腿,但是当我们有两只同名的猫时,我不想这样做。

我尝试过这样的事情:

select  a.animal, b.legs, a.name
from animallistA as a join animallistB as b
on a.name = b.name 
where b.legs = 4 and not b.legs = 3
group by a.animal, b.legs, a.name

如果我说where b.legs = 4,那么我也会收到保罗'但如果我说where b.legs = 4 and not b.legs = 3我什么也得不到。

有没有办法不接受同名和4条腿而不是同名但只有4条或更少腿的猫。

4 个答案:

答案 0 :(得分:1)

NOT EXISTS可以胜任。

SELECT t1.animal, t2.legs, t2.name
FROM t1
JOIN t2 ON t1.name = t2.name
WHERE t2.legs = 4 AND 
      NOT EXISTS 
      (
          SELECT 1 FROM t2 WHERE t2.name = t1.name AND t2.legs != 4
      )

答案 1 :(得分:1)

您可以先获取4条腿动物的所有唯一名称(来自子查询),然后加入主表以获得所需的结果。

    select  a.animal, b.legs, a.name from animallistA as a join 
    (select name,max(legs) legs from animallistB  group by name having count(distinct legs)=1) as b
     on a.name = b.name and b.legs=4

从子查询中我们可以得到结果

Legs   Name
4      Miau
4      Peter

因为Paul的条件中的不同值失败。将其与主表连接会得到请求的结果

答案 2 :(得分:0)

据我了解你的问题,我建议跟随查询:

SELECT A.ANIMAL, A.NAME, B.LEGS 
FROM ANIMALLISTA A
INNER JOIN ANIMALLISTB B ON A.NAME = B.NAME
LEFT JOIN (SELECT NAME, COUNT(*) AS RC FROM ANIMALLISTB GROUP BY NAME) C ON A.NAME = C.NAME
WHERE B.LEGS=4
 AND C.RC=1

输出:

ANIMAL  NAME    LEGS
Cat Miau    4
Cat Peter   4

答案 3 :(得分:0)

  

你可能想尝试这样的东西,在My SQL 8.0.2上为我工作   || cat_1 = T1和cat_2 = T2

WITH CTE AS 
(
SELECT distinct * 
FROM cat_1 
INNER JOIN cat_2 ON cat_1.names=cat_2.name
),

SCTE AS
(
SELECT CTE.animal, 
CTE.legs, 
CTE.names, 
COUNT(CTE.names) over(PARTITION BY CTE.names) as Count
from CTE
)

SELECT 
SCTE.animal, 
SCTE.legs, 
SCTE.names
FROM SCTE
WHERE legs = 4
AND Count = 1; 

输出:

animal   legs   names
Cat       4     Miau
Cat       4     Peter