简体   繁体   中英

many to many table join mysql

i have three tables:

mails

+-----+----------+----------------+
| id  | chain_id | subject        |
+-----+----------+----------------+
| 108 |      108 | aaa            |
| 109 |      109 | Chain          |
| 110 |      110 | New            |
| 111 |      108 | aaa            |
| 112 |      108 | Re: Re:  aaa   |
| 113 |      109 | Chain          |
| 114 |      114 | Fwd: Subject   |
| 115 |      108 | Fwd: aaa       |
| 116 |      108 | Re: aaa        |
| 117 |      108 | Fwd: aaa       |
+-----+----------+----------------+

chain_tags

+----+----------+--------+
| id | chain_id | tag_id |
+----+----------+--------+
|  1 |      108 |     15 |
|  2 |      108 |     16 |
+----+----------+--------+

mail_tags

+----+--------+---------+
| id | name   | color   |
+----+--------+---------+
| 15 | First  | #ffdaef |
| 16 | Second | #aed9ff |
+----+--------+---------+

I want to select all records from mails table, mail_tags.color , mail_tags.name , and the quantity of records with the same chain_id , group by mails.chain_id , but after group by i want to leave the latest records (with the biggest id).

I managed to write this query

SELECT
        *,
        COUNT(*) AS quantity
    FROM
        (SELECT
            *
        FROM
            mails
        ORDER BY id DESC) AS t
    GROUP BY chain_id
    ORDER BY id DESC

it returns last rows group by chain_id with total quantity of mails in that chain, but i don't know how to join tag names and tag colors for each record. Some of the records might have few tags, some none.

I'm not too sure if I understood the exact requirement but something along these lines should work:

select x.id, x.chain_id, x.subject, count, mt.name, mt.color from
(
select m.*,count(*) count,max(mt.id) maxid
   from mails m
left outer join chain_tags ct on (m.chain_id=ct.chain_id)
left outer join mail_tags mt on (ct.tag_id=mt.id)
  group by m.chain_id
) x
left join mail_tags mt on x.maxid=mt.id

basically the idea is to obtain the count and the max mail_tag id by chain_id, which is done within the inner query and once we know the max mail tag id we can join back to mail_tags and get the name and color, which is done by the left join in the main query. Hope this helps

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