在WHERE中使用SELECT中的值

时间:2015-12-26 23:21:27

标签: mysql sql

所以我选择了一个名称和一些与之相关的体育项目,我只需要在体育数量大于1时选择它们。

SELECT DISTINCT name AS FullName,  
      (SELECT COUNT(id) FROM coaches WHERE coaches.name=FullName) AS NrOfSports  
FROM coaches WHERE NrOfSports>1

如果WHERE被移除,则查询工作正常,并显示其中一些只有" 1"作为NrOfSports。当我将其添加到WHERE子句时,我收到错误,因为它无法识别。这让我感到困惑,因为如果我在另一个SELECT列中使用它,它会正常工作。

有办法做到这一点吗?它不依赖于软件。

3 个答案:

答案 0 :(得分:5)

改为使用Group ByHaving

SELECT name AS FullName, 
   COUNT(id) AS NrOfSports 
FROM coaches 
GROUP BY name
HAVING COUNT(id) > 1

您的相关查询可以正常工作,您只需将其移动到子查询,然后就可以添加where条件。但是,我相信group by会更快。

答案 1 :(得分:2)

错误说明

您收到错误,因为WHERE子句无法在同一级别按别名访问列。有两个解决方案,我不推荐,但为了你的问题,我附上了:

(1)将您的WHERE NrOfSports > 1移至另一个级别

SELECT *
FROM (
    SELECT DISTINCT 
        name AS FullName,  
        ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) AS NrOfSports  
    FROM coaches c1
    ) foo
WHERE NrOfSports > 1

(2)在同一级别使用您的情况。

SELECT DISTINCT
    name AS FullName,
    ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) AS NrOfSports 
FROM 
    coaches c1
WHERE
    ( SELECT COUNT(id) FROM coaches c2 WHERE c1.name = c2.name ) > 1

这样可以解决错误,但仍然效率不高(!)

更好的方法

相反,您可以将GROUP BY的强大功能与其自己的名为HAVING的WHERE子句相结合,将输出限制为只有nameid的{​​{1}}

SELECT DISTINCT 
  name AS FullName,
  count(id) AS NrOfSports 
FROM
  coaches 
GROUP BY
  name
HAVING 
  count(id) > 1

答案 2 :(得分:2)

sgeddes的答案比我的好。但你也可以这样做:

    SELECT * 
    FROM (
       SELECT DISTINCT name AS FullName,  
             (SELECT COUNT(id) FROM coaches WHERE coaches.name=FullName) AS NrOfSports  
       FROM coaches  
   ) tmp  
     WHERE NrOfSports>1