引用MySQL计算/动态列或子查询

时间:2011-08-02 10:56:10

标签: mysql sql subquery

我有两张桌子 - 小册子和小册子。每个销售线索都可以申请零个或多个小册子。我可以编写以下查询来获取每个潜在客户请求的小册子数量:

SELECT
    id,
    (SELECT COUNT(*) FROM brochures WHERE lead = l.id) AS 'BrochureCount'
FROM leads l

如果我只想显示已经请求过一些小册子的潜在客户,我可以在WHERE子句中重复子查询:

SELECT
    id,
    (SELECT COUNT(*) FROM brochures WHERE lead = l.id) AS 'BrochureCount'
FROM leads l
WHERE
    (SELECT COUNT(*) FROM brochures WHERE lead = l.id) > 0

但这可能会使子查询运行两次,从而导致查询速度更慢。

是否可以通过名称,列号或其他格式在WHERE子句中引用BrochureCount

感谢您的时间,

亚当

4 个答案:

答案 0 :(得分:1)

我找到了所谓的内容,并且无法完成。

它被称为列别名,显然它不能用在WHERE子句中。来自MySQL docs

  

标准SQL不允许您引用WHERE中的列别名   条款。强制执行此限制是因为WHERE代码是   执行后,列值可能尚未确定。

答案 1 :(得分:0)

他们订购的销售线索和手册数量至少为1:

SELECT
  leads.id,
  COUNT(brochures.lead) AS `BrochureCount`
FROM
  leads
INNER JOIN
  brochures
ON
  leads.id = brochures.lead
GROUP BY
  leads.id

如果您想要所有的潜在客户和宣传册,即使他们有0张相关的小册子:

SELECT
  leads.id,
  COUNT(brochures.lead) AS `BrochureCount`
FROM
  leads
LEFT OUTER JOIN
  brochures
ON
  leads.id = brochures.lead
GROUP BY
  leads.id

答案 2 :(得分:0)

尝试以下方法:

SELECT id, BrochureCount
FROM(
    SELECT id, (SELECT COUNT(*) FROM brochures WHERE lead = l.id) AS 'BrochureCount'
    FROM leads l) data
Where data.BrochureCount > 0

答案 3 :(得分:0)

引用计算列的最直接的方法是使用HAVING子句。一般来说:

<subquery> HAVING <expression>

相当于

SELECT * from (<subquery>) WHERE <expression>