mysql - 如何在 SQL 中为别名列指定条件

标签 mysql sql alias

如何在此查询中为具有别名的列指定条件?

我的查询:

select
cnt.id as content_id,
cnt.title as content_title,
cnt.introtext,
cnt.fulltext,
cnt.ordering,
cnt.images,
cnt.alias,
cnt.state,
cnt.catid,
f.item_id,
cat.id as cat_id,
cat.title as cat_title,
max(case when f.field_id = 1 then f.value end) as inslider,
max(case when f.field_id = 2 then f.value end) as sliderquote
from snm_fields_values f
join snm_content cnt
on cnt.id = f.item_id
join snm_categories cat
on cnt.catid = cat.id
where cnt.state = 1
and f.value = 'ja'
group by f.item_id
order by f.item_id, inslider

这将返回以下内容:

enter image description here

sliderquote 为 NULL,因为它检查 f.value 是否等于“ja”,但它从不这样做。如果我删除条件,我会得到该行中的正确数据,但我需要条件。

我怎样才能仍然拥有它并仅将其应用于sliderquote

AND sliderquote = 'ja' 不起作用,因为 SQL 不会像我学到的那样读取别名。

我能做什么?

最佳答案

我认为您可能需要一个嵌套请求,如下所示:

SELECT *
FROM   (SELECT cnt.id    AS content_id,
               cnt.title AS content_title,
               cnt.introtext,
               cnt.fulltext,
               cnt.ordering,
               cnt.images,
               cnt.alias,
               cnt.state,
               cnt.catid,
               f.item_id,
               cat.id    AS cat_id,
               cat.title AS cat_title,
               Max(CASE
                     WHEN f.field_id = 1 THEN f.value
                   END)  AS inslider,
               Max(CASE
                     WHEN f.field_id = 2 THEN f.value
                   END)  AS sliderquote
        FROM   snm_fields_values f
               JOIN snm_content cnt
                 ON cnt.id = f.item_id
               JOIN snm_categories cat
                 ON cnt.catid = cat.id
        WHERE  cnt.state = 1
        GROUP  BY f.item_id
        ORDER  BY f.item_id,
                  inslider)T
WHERE  T.sliderquote = 'ja' 

关于mysql - 如何在 SQL 中为别名列指定条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049329/

相关文章:

sql - 如何设计数据库约束,以便两个实体只有在两个字段值匹配时才能具有多对多关系?

SQL 查询 GETGATE() 和 DATEPART 格式

sql - SELECT * FROM table WHERE field IN(array) - H2 数据库

oracle - 使用前缀为查询中的所有列别名

jQuery 就绪函数别名

mysql最好的备份方法?以及如何将备份转储到目标目录

MySQL - 仅当前一行字段为 0 时才选择行?

bash - 非交互式 bash 中的别名

php - 将 MySQL 查询结果合并为一条记录

php - 使用 PHP 制作 'facebook' 样式提要