0

我有以下查询。

SELECT parent.id AS 'id', parent.CA_NAME as 'name', node.level AS 'level', midpoint.level AS 'midpointlevel', SUM(ad.id IS NOT NULL) AS 'count'
FROM
category AS parent,
category AS midpoint,
category AS node
LEFT JOIN ad ON ad.id=node.id
AND ad.status='A'
WHERE (node.`LEFT` BETWEEN parent.`LEFT` AND parent.`RIGHT`)
AND (node.`LEFT` BETWEEN midpoint.`LEFT` AND midpoint.`RIGHT`)
AND midpoint.id='1'
GROUP BY parent.id
HAVING IF(midpoint.level=0, node.level < 2, node.level > 0)
ORDER BY parent.id

我不想选择该midpoint.level AS 'midpointlevel'部分,但如果我删除它,having 子句会给出一个错误提示:错误代码:1054。'having 子句'中的未知列'midpoint.level'。谁能帮我删除不需要的选择部分。

4

3 回答 3

1

最简单的方法是使用简单的子查询:

SELECT id, 
       name,
       -- midpointlevel,  <-- commented out, since we don't need this column 
       level, 
       count
FROM (
  SELECT parent.id AS 'id', parent.CA_NAME as 'name', node.level AS 'level',  midpoint.level AS 'midpointlevel', SUM(ad.id IS NOT NULL) AS 'count'
  FROM
  category AS parent,
  category AS midpoint,
  category AS node
  LEFT JOIN ad ON ad.id=node.id
  AND ad.status='A'
  WHERE (node.`LEFT` BETWEEN parent.`LEFT` AND parent.`RIGHT`)
  AND (node.`LEFT` BETWEEN midpoint.`LEFT` AND midpoint.`RIGHT`)
  AND midpoint.id='1'
  GROUP BY parent.id
  HAVING IF(midpoint.level=0, node.level < 2, node.level > 0)
  ORDER BY parent.id
) subquery
于 2013-10-26T09:38:40.873 回答
0

SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value;

参考上面的语法

于 2013-10-26T09:33:13.843 回答
0

如果将其添加到 GROUP BY,则可以将其从选择中删除。不熟悉 HAVING IF。尝试这个:

GROUP BY parent.id,midpoint.level
HAVING (midpoint.level=0 AND node.level < 2 AND node.level > 0)
ORDER BY parent.id
于 2013-10-26T09:42:57.863 回答