[英]join two tables in mysql and get records
I have two tables " contacts " and " users ". 我有两个表“ 联系人 ”和“ 用户 ”。 Users table storing data with "," separated.
用户表存储的数据之间用“,”分隔。 Need to distinct data in " Contacts " column from " Contacts " table.
需要在“ 联系人 ”表的“ 联系人 ”列中区分数据。 And need to join with " Users " table, and get the records.
并且需要与“ Users ”表联接,并获取记录。
Contacts Table
--------------------------
id | user_Id | contats
--------------------------
1 | 2147483647 | 90123456789,90123456789,90123456789,90123456789
2 | 2147483647 | 90123456789,90123456789,90123456789,90123456789
3 | 919444894154 | 90123456789,90123456789,90123456789,90123456789
Users Table
-----------------------------
id | username | email | phone
-----------------------------
1 | bhavan | bhavanram93@gmail.com | 90123456789
2 | bhavan | bhavanram93@gmail.com | 90123456789
3 | prince | prince@gmail.com | 1234567980
4 | bhavan | bhavanram93@gmail.com | 90123456789
5 | hello | hello@gmail.com | 1234567890
6 | bhavan | bhavanram93@gmail.com | 90123456789
Your table Contacts
shouldn't be constructed this way. 您的表格
Contacts
不应该以这种方式构造。
Since you want 1 Users
table containing all the data about a user, and 1 Contacts
table containing links between different users, you'd rather do this kind of table structure : 由于您想要1个
Users
表包含一个用户的所有数据,并且1个Contacts
表包含不同用户之间的链接,因此您希望使用这种表结构:
Contacts table 联系人表
id | user_id | contact_id
-------------------------
1 | 1 | 2
2 | 1 | 3
3 | 2 | 3
That'll allow you to do something like : 这样您就可以执行以下操作:
SELECT *
FROM Users
JOIN Contacts ON (Users.id = Contacts.contact_id)
WHERE Contacts.user_id = 1
Which will return all the data of the contacts of the user 1. 它将返回用户联系人的所有数据1。
Your current structure is a huge ongoing mess, it's the opposite of being flexible. 您当前的结构是一个持续不断的混乱局面,与灵活性相反。
You should restructure your db to a normalized format as Steve suggest. 您应该按照Steve的建议将数据库重组为规范化格式。
But if you cant: 但是,如果您不能:
SELECT *
FROM Users
JOIN Contacts
ON CONCAT(',', Contacts.contacts, ',') like
CONCAT('%,', Users.phone, ',%')
WHERE Contacts.user_id = 1
the idea is you convert your contacts to 想法是您将联系人转换为
, <numbers> ,
,90123456789,90123456789,90123456789,90123456789,
and try to match with 并尝试与
%,90123456789,%
Note this approach cant use any index so will have bad performance with many rows. 请注意,此方法不能使用任何索引,因此在许多行中都将具有较差的性能。 if you are in the order of 1k-10k rows may be ok.
如果您的顺序为1k-10k,则行可以。 More than that you need consider restructure your db.
除此之外,您还需要考虑重组数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.