简体   繁体   中英

How do I join two tables by string?

I need to join two tables on the basis of a string of IDs. This is my query so far.

SELECT sc.size_id from subcategories s 
join categories c on c.id = s.categories_id 
join size_categories sc on sc.categories_id = c.id ;

The result is

size_id 
1,2,5       
1,2,5   
4,2,1   
4,2,1   
1,2,5   
1,2,5       
4,2,1   
4,2,1   
4,2,1   
4,2,1   
7,2,9       
3,4,6   
3,4,5   

sc.size_id is a string with values like => 1,2,3 I need to join other table and fetch the names based on the above IDs in string. The table name is sizes, whose values are like

id    name
1     2m
2     3m
3     4m

I tried this, but can't get the value

SELECT sz.name,sc.size_id from subcategories s 
join categories c on c.id = s.categories_id 
join size_categories sc on sc.categories_id = c.id 
join sizes sz on (find_in_set(sz.id,sc.size_id)>0)

My size_categories table is

id     size_id   categories_id  
1       1,2,5              1    
    
    
    
    
2       9,2,8               2   
    
    
    
    
3      3,4,6               3    
    
    
    
    
4      4,2,1                4   

I think I need to use group_concat, but it groups everything, so group_by could be better, but how should I use it? Thank You

You can use group_concat with a group by on sc.size_id

select s.name,sc.size_id,group_concat(sz.name)
from subcategories s 
join categories c on c.id = s.categories_id 
join size_categories sc on sc.categories_id = c.id 
join sizes sz on (find_in_set(sz.id,sc.size_id)>0)
group by s.name,sc.size_id

If you still get duplicate size names use distinct inside group_concat

You should normalize your schema DO NOT store relations as comma separated values.

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