简体   繁体   中英

how to get user name based on id separated by comma in single table

user_id   user_name        user_friend_list
1         dharmendra       2,3,4,5,6,7
2         jitendra         1,3,4,5,6,7
3         xyz              1,2,6,7 
4         pqr              1,3,4 

now i want to extract user_id & user name based on user_friend_list id 6 ie it will return 1,2,3 user_id & user name dharmendra jitendra and xyz.

i simply use splite function of php but it is so complicated please provide me well shortcut method

thanks & regards

You can use FIND_IN_SET()

select user_id, user_name
from your_table
where find_in_set(6, user_friend_list) > 0

But it would actually be better to change your table design. Never store multiple values in one column!

first thing the table is not normalized that's why the problem exist you must break this table like this or better :)

table 1
user_id
user_name

table 2
user_id
friend_id

table 2 will have some redundant data though which can be removed by adding a third table as a mapping between table1 and table2

now you can have the following query to get the result

select user_id,user_name from table1 as a join table2 as b on a.user_id=b.user_id where b.friend_id=6;

“从表中选择user_id,用户名,其中user_id IN(2,3,4,5,6,7)”;

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