mysql concat 条件,MySQL:GROUP_CONCAT结果的条件?

I have an SQL setup akin to the following:

ARTICLES

id (PK)

name

TAGS

id (PK)

tag

...and a third table logging associations between the two, since there can be multiple tags to each article:

ARTICLE_TAG_ASSOCS

id (PK)

article_id (FK)

tag_id (FK)

Question: how to find articles that have a particular tag?

The best I could come up with was this:

SELECT

name, GROUP_CONCAT(CASE WHEN tag = 'some-tag' THEN tag ELSE NULL END) AS tags

FROM

articles, tags, article_tag_assocs

WHERE

articles.id = article_id && tags.id = tag_id && tags IS NOT NULL

GROUP BY

article_id

That's on the right lines; if an article doesn't have the tag "some-tag" then that column shows up with a null value in the "tags" column. But how can I eliminate that row completely?

Naturally, I tried appending

&& tags NOT LIKE '%some-tag%'

...to my WHERE clause, before learning that you can't use GROUP_CONCAT aliases in WHERE clauses. So I tried appending:

HAVING tags IS NOT NULL;

...to the query, with the same result, i.e. MySQL says it doesn't recognise the column "tags".

Any help appreciated.

解决方案

How about this?

SELECT distinct a.name

FROM articles a join

article_tag_assocs ata

on a.id = ata.article_id join

tags t

on t.id = ata.tag_id

WHERE t.tag = 'some-tag';

It answers your question quite directly.

Note that this also introduces table aliases. These make the query easier to write and to read.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值