1

我使用一些这样的sql:

SELECT COALESCE(group.display,item.display) as display....

我想在 WHERE 子句中添加:

WHERE display='1'

WHERE 显示是合并的结果。

同样,我希望能够对这样的事情做同样的事情:

IF(ISNULL(gd.group_main_image),p.main_image,gd.group_main_image) AS image
... WHERE image IS NOT NULL

请问我该怎么做?

4

3 回答 3

3

您不能在同一级别的查询中使用别名。

你必须重复自己。

WHERE COALESCE(group.display,item.display) = '1'

编辑

好吧,我限制得太多了。您可以在 MySql 的 having 子句中使用别名。您不能在其他 DBMS(Oracle、SQl Server)中做到这一点。通常它在 ANSI SQL 中也是不允许的。

于 2012-07-04T10:06:36.180 回答
0

As described in Problems with Column Aliases:

An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column:

SELECT SQRT(a*b) AS root FROM tbl_name
  GROUP BY root HAVING root > 0;
SELECT id, COUNT(*) AS cnt FROM tbl_name
  GROUP BY id HAVING cnt > 0;
SELECT id AS 'Customer identity' FROM tbl_name;

Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:

SELECT id, COUNT(*) AS cnt FROM tbl_name
  WHERE cnt > 0 GROUP BY id;

The WHERE clause determines which rows should be included in the GROUP BY clause, but it refers to the alias of a column value that is not known until after the rows have been selected, and grouped by the GROUP BY.

于 2012-07-04T10:09:13.797 回答
0

您不能在子句中使用列别名WHERE

所以:

WHERE COALESCE(group.display,item.display)='1'

或者:

HAVING display='1'

但是,HAVING在发现所有结果集之后执行,所以基本上这会更消耗内存

于 2012-07-04T10:06:55.310 回答