我有这个查询检查从搜索文本框输入的每个关键字,并且必须返回最匹配的关键字。 我已经使查询和它的工作正常。问题是,我想在返回的行中排除所有带有0值的KW_MATCHED。
SELECT
A1.*, (
SELECT
sum(
CASE
WHEN (A1.ID = A2.tag_id)
AND (
A2.keyword = 'keyword1' || A2.keyword = 'keyword2'
) THEN
1
ELSE
0
END
)
FROM
tbl_article_tags A2
) AS KW_MATCHED
FROM
tbl_article A1
ORDER BY
KW_MATCHED DESC
结果:
+----+---------------+----------------+------------+
| ID | Title | Content | KW_MATCHED |
+----+---------------+----------------+------------+
| 1 | title | Lorem Ipsum... | 7 |
+----+---------------+----------------+------------+
| 2 | another title | Lorem Ipsum... | 5 |
+----+---------------+----------------+------------+
| 3 | another title | Lorem Ipsum... | 0 |
+----+---------------+----------------+------------+
| 4 | another title | Lorem Ipsum... | 0 |
+----+---------------+----------------+------------+
我尝试重新使用Alias KW_MATCHED作为WHERE子句(请参阅下面的查询),但它会返回以下消息:
[Err] 1054 - 未知列' KW_MATCHED'在' where子句'
SELECT
A1.*, (
SELECT
sum(
CASE
WHEN (A1.ID = A2.tag_id)
AND (
A2.keyword = 'keyword1' || A2.keyword = 'keyword2'
) THEN
1
ELSE
0
END
)
FROM
tbl_article_tags A2
) AS KW_MATCHED
FROM
tbl_article A1
WHERE
KW_MATCHED > 0
ORDER BY
KW_MATCHED DESC
有什么办法吗?谢谢你的先进和对不起我的坏英语:)
答案 0 :(得分:0)
尝试使用HAVING而不是WHERE
SELECT
A1.*,
(SELECT sum(case when (A1.ID=A2.tag_id) AND (A2.keyword='keyword1' || A2.keyword='keyword2') then 1 else 0 end) FROM tbl_article_tags A2) as KW_MATCHED
FROM tbl_article A1
HAVING KW_MATCHED > 0
ORDER BY KW_MATCHED DESC