如何在此查询中为具有别名的列提供条件?
我的查询:
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没有像我所学到的那样读取别名。
我该怎么办?
答案 0 :(得分:1)
我认为您可能需要嵌套请求,如下所示:
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'