SQL joint table query LEFT JOIN data deduplication

When querying tables using left join, if one record in table1 corresponds to multiple records in table2, multiple records with the same id will be found repeatedly.

SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.tid

Solution:

Use the query result as an intermediate table and use group by to deduplicate

SELECT tmp.* FROM (
SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.tid
) tmp group by tmp.id

If you want to calculate count for the data after group by, you can use the query result as an intermediate table and then calculate count

SELECT COUNT(1) FROM (
SELECT tmp.* FROM (
SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.tid
) tmp group by tmp.id
) tmp2

Guess you like

Origin blog.csdn.net/watson2017/article/details/130007731