子查询mysql

时间:2010-02-24 16:21:54

标签: mysql

如果我有这样的表:

yr          subject  
1960    Physics
1960    Chemistry
1961    Physics
1962    Chemistry

我希望所有这些年都是物理而不是化学

如果我试试这个,它不会给我正确的结果。

select yr from table where subject = "Physics" and  
yr NOT IN (select yr from table where subject = "Chemistry")

5 个答案:

答案 0 :(得分:1)

sqlzoo的问题有点棘手,因为1933年有不止一个物理奖。所以,正确答案是:

select distinct yr from nobel as n1
where subject = 'Physics' 
and not exists 
   (select 1 from nobel as n2 where n2.subject = 'Chemistry' and n2.yr = n1.yr)

您可以使用此查询检查1933年的结果:

select * from nobel where yr = 1933

答案 1 :(得分:0)

您的查询存在的问题是,您返回两年的两次物理奖励返回的年份。添加DISTINCT关键字只会为您提供年份(根据question 3A on this site

SELECT DISTINCT yr FROM nobel 
WHERE 
  subject = 'Physics' AND 
  yr NOT IN (SELECT yr FROM nobel WHERE subject = 'Chemistry');

答案 2 :(得分:0)

试试这个:

select yr from table t1 where subject = 'Physics'
where not exists
(select yr from table t2 where subject = 'Chemistry' and t1.yr = t2.yr)

答案 3 :(得分:0)

这个解决了您的链接所述的问题:

SELECT DISTINCT n1.yr 
FROM nobel n1
WHERE n1.subject = 'Physics'
AND n1.yr NOT IN (
  SELECT DISTINCT n2.yr
  FROM nobel n2
  WHERE n2.subject = 'Chemistry'
)

这个工作的原因是因为它消除了重复的年份。由于价格可以由同一年的多个人和主题授予,因此您希望删除重复项。您还可以跳过内部查询的DISTINCT,这将跳过一个排序步骤。在生产中,您需要分析此查询并创建正确的索引。

答案 4 :(得分:0)

你几乎就在那里......你需要使用不同的东西:

select distinct yr from table where subject = "Physics" and  
yr NOT IN (select yr from table where subject = "Chemistry")

对于给出的链接:

select distinct yr from nobel 
where subject = 'Physics' and 
yr not in (select yr from nobel where subject = 'Chemistry')