在SQL查询的WHERE子句中使用自定义字段

时间:2009-08-19 01:53:48

标签: sql mysql

我的问题与此问题非常相似How to reference a custom field in SQL我有以下问题:

SELECT * , (SELECT COUNT( id ) 
FROM cms_store_items
WHERE speaker = cms_store_items_speakers.id
) AS count
FROM cms_store_items_speakers
LIMIT 0 , 30

我需要添加一个看起来像WHERE count > 0的WHERE子句,但是当我这样做时,我得到错误Unknown column 'count' in 'where clause'无论如何我在where子句中引用自定义字段而没有重复逻辑?< / p>

我可以在我的代码中放置where子句的逻辑,但如果不需要,我不想向应用程序发送可能超过1000行的内容,这似乎是浪费资源。

3 个答案:

答案 0 :(得分:16)

嗯,严格按照你的方式做到这一点:

select
*
from
(
    SELECT * , (SELECT COUNT( id ) 
    FROM cms_store_items
    WHERE speaker = cms_store_items_speakers.id
    ) AS count
    FROM cms_store_items_speakers
) a
where a.count > 0
LIMIT 0 , 30

但是,做以下事情可能会更好。它充分利用了having子句:

select
    s.id,
    s.col1,
    count(i.speaker) as count
from
    cms_store_items_speakers s
    left join cms_store_items i on
        s.id = i.speaker
group by
    s.id,
    s.col1
having
    count(i.speaker) > 0
limit 0, 30

答案 1 :(得分:11)

您可以改为使用HAVING子句:

...
) AS count
FROM cms_store_items_speakers
HAVING count > 0
LIMIT 0 , 30

HAVINGWHERE类似,但它可以处理计算的列。 警告: HAVING通过修剪 其余查询后的结果,它不能替代WHERE子句。< / p>

答案 2 :(得分:0)

我不是100%肯定mysql,但这样的事情应该是非常可能的:

(SELECT 
     *
FROM
(
   SELECT cms_store_items_speakers.*,
          (SELECT COUNT(id) FROM cms_store_items
           WHERE speaker = cms_store_items_speakers.id) AS 'count'
   FROM cms_store_items_speakers)
   LIMIT 0, 30
)
WHERE count > 0;