I have 2 tables which is user
and userdata
.
Once a customer buy a product, it will insert into table userdata
and user
.
In user
table , the product id is recorded in user
. buyid
in form of "id, id ,id ,id ,id".
example : "23, 24". So I have tried to get all rows with id ( 23, 24 ) from product by using these queries
SELECT * FROM `userdata`,`user` WHERE `userdata`.`id` IN (`user`.`buyid`);
Query return 1 row product which is id=23
SELECT * FROM `user` INNER JOIN `userdata` ON `userdata`.`id` IN (`user`.`buyid`);
This too return only 1 row of product with id 23.
Expected result each row return this:
user.id | user.name | user.contact | product.id | product.name
1 | nazmi | 99999 | 23 | A
1 | nazmi | 99999 | 24 | B
Fix your data model! Storing lists of ids in a string is bad, bad, bad:
Sometimes, you are stuck with other people's really, really, really bad decisions. MySQL offers a nice function (too nice in my opinion) to help:
SELECT *
FROM user u JOIN
userdata ud
ON find_in_set(ud.id, u.buyid) > 0;
If you have spaces in your id list, then you need to get rid of them. And the separator has to be a comma.
SELECT *
FROM user u JOIN
userdata ud
ON find_in_set(ud.id, replace(u.buyid, ' ', '')) > 0;
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.