简体   繁体   中英

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:

--------------------------
| 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 .


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.

Let me know if the query returns the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM