MYSQL A, B associated query table array

Final Results:


 

Database Table

A table:

Table B:

 


 

Steps

The main keyword: FIND_IN_SET, GROUP_CONCAT, LEFT JOIN, the GROUP BY

 

The first step: left join table AB connected by its associated ID find_in_set

select us.id,us.name,us.hobbyId,hb.name hobby
from hobby hb
left join user us on find_in_set(hb.id,us.hobbyId)

 

The results: name Field name a lot of repetitions, do the deduplication processing

 

Step two: go heavy GROUP BY

select us.id,us.name,us.hobbyId,hb.name hobby
from hobby hb
left join user us on find_in_set(hb.id,us.hobbyId) GROUP BY(us.name)

 

Results: This is the name already grouping, but not on the hobby and hobbyId

 

 

The third step: Use GROUP_CONCAT

select us.id,us.name,us.hobbyId,GROUP_CONCAT(hb.name) hobby
from hobby hb
left join user us on find_in_set(hb.id,us.hobbyId) GROUP BY(us.name) ORDER BY us.id

 

Guess you like

Origin www.cnblogs.com/zhcblog-20181026/p/11261665.html