[英]mysql left join with count(on right table attribute) group by
I have two tables, one with tags and another one with the actually selected tags of an article (table relation). 我有两个表,一个带有标签,另一个带有标签(表关系)的实际选择的标签。 I want to add the condition to select the amount of the actually selected tags of the current article.
我想添加条件以选择当前文章的实际选择的标签数量。 example selecting article 1:
选择文章1的示例:
--------------------------
| id | name | selected |
--------------------------
| 0 | this | 1 |
| 1 | is | 0 |
| 2 | sparta | 1 |
--------------------------
Ive got to this far: 我到目前为止:
SELECT t.*, count(t.id) as `selected`
FROM tag t LEFT JOIN relation r ON t.id = r.tid
GROUP BY t.id
table tag: 表格标签:
---------------
| id | name |
---------------
| 0 | this |
| 1 | is |
| 2 | sparta |
---------------
table relation: 表关系:
-------------
| tid | aid |
-------------
| 0 | 2 |
| 0 | 1 |
| 2 | 1 |
-------------
EDIT : The first query returns the selected tags for an article and that's not the desired behaviour 编辑:第一个查询返回所选的文章标签,这不是所需的行为
Is that the query you're looking for? 您正在寻找的查询吗?
SELECT A.id
, COUNT(T.id) AS [nb selected tags]
FROM article A
LEFT OUTER JOIN relation R ON R.aid = A.id
LEFT OUTER JOIN tag T ON T.id = R.tid
AND T.selected = 1
GROUP BY A.id
Hope this will help you. 希望这会帮助你。
PS: If you just want the result of a specific Article, you juste have to add a WHERE
clause before the GROUP BY
. PS:如果只需要特定文章的结果,则只需在
GROUP BY
之前添加WHERE
子句。
Query returning the desired data: 查询返回所需数据:
SELECT T.id
,T.name
, CASE
WHEN R.tid IS NOT NULL THEN 1
ELSE 0
END AS [selected]
FROM tag T
LEFT OUTER JOIN relation R ON R.tid = T.id
AND R.selected = 1
AND R.aid = ...
I assume that the table relation
has a unicity on tid and aid. 我假设表
relation
在提示和帮助上具有统一性。
Let me know if the query returns the expected result. 让我知道查询是否返回预期结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.