简体   繁体   中英

Select Distinct using a join

 select DISTINCT cid,cname,tid from colors c left join tags t on t.tname = c.cname; 

colors:

cid cname

1 red

2 blue

3 green

tags:

tid tname

1 red

2 red

3 blue

4 green

Current Result:

1 red 1

1 red 2

2 blue 3

3 green 4

Expected Result:

1 red 1

2 blue 3

3 green 4

This query should match your expected result

select cid,cname,tid
from colors c
left join tags t on t.tname = c.cname;
group by c.cid
select 
    cid, cname, tid
from
    colors c
        left join
    tags t ON t.tname = c.cname
GROUP BY c.cname,c.cid,t.tid;

GROUP BY tag name

select DISTINCT cid,cname,tid
from colors c
left join tags t on t.tname = c.cname;
GROUP BY t.name

I dont have mysql to try this but this should help you. One more thing is you can not directly use tid into your query you need to take count of it.

select  cid, cname, count(tid)
    from Color c
    left join tags t on t.name = c.cname
GROUP BY cname;

here is sqlFiddle for it

Use group by

select cid,cname,tid
from colors c
left join tags t on t.tname = c.cname
group by cid,cname,tid;

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