如何在此查询中为具有别名的列指定条件?
我的查询:
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
这将返回以下内容:
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'