gpt4 book ai didi

php - 连接两个表时遇到问题

转载 作者:行者123 更新时间:2023-11-29 23:55:23 25 4
gpt4 key购买 nike

我有两个表用户和联系人,其中注册用户使用 csv 添加记录以及联系人表中的 ID。

我的表结构

用户

id   name     phone_no  verify
1 sachin 123 yes
2 max 345 yes
3 john 99 yes

联系人

contacts_id   name    phone_no   user_id
1 xyz 345 1
2 abc 123 2
3 john 99 1

结果

1) search phone_no '123' from contacts table

contacts_id name phone_no user_id
2 abc 123 2

2) i got my number '123' in 2nd row will check who has my number so got user_id='2'

3) now i have checked whether 'max' (id='2') has phone_no ('123') in contacts table

4) So max phone_no is '345'

contacts_id name phone_no user_id
1 xyz 345 1

5)我得到最大数字“345”,保存为“xyz”(无关紧要),user_id=“1”,即sachin

6)所以我只想让那些拥有我的号码并且他们也拥有我的号码的用户。(最终结果)

最佳答案

我相信你需要重新设计你的模式,因为(据我所知)你有一个主用户表,并且你有一个功能允许用户添加其他用户作为他的联系人,所以你需要保留跟踪哪些用户是哪些其他用户的联系人。

表联系人不需要保存姓名或号码。该数据必须始终来自用户表以确保一致性。

用户

id   name     phone_no  verify
1 sachin 15123 yes
2 max 26345 yes
3 john 37345 yes
4 peter 48345 yes
5 sam 59345 yes

联系人

relation_id  relation_owner   relation_target
1 1 2
2 1 3
3 2 3
4 2 4
5 2 5
6 3 1

这样,您要回答的问题将通过以下查询得到解决

select u1.name as me, 
u2.name as contact
from users u1
join contacts c1 on u1.id=c1.relation_owner
join contacts c2 on c2.relation_owner=c1.relation_target and c2.relation_target=c1.relation_owner
join users u2 on c2.relation_owner=u2.id
where u1.id=:userid

现在,如果我尝试对您的架构执行相同的操作。

用户

id   name     phone_no  verify
1 sachin 123 yes
2 max 345 yes

联系人

id   name    phone_no   user_id
1 xyz 345 1
2 abc 123 2

编辑澄清后

获取用户 1 (sachin) 的联系人

select u1.name as me, 
u2.name as contact
from user u1
join contacts c1 on u1.phone_no = c1.phone_no
join user u2 on c1.user_id=u2.id
where user.id=1

获取用户 sachin 的联系人,而该用户的联系人中也有 sachin

select u1.name as me, 
u2.name as contact
from user u1
join contacts c1 on u1.phone_no = c1.phone_no
join user u2 on c1.user_id=u2.id
join contacts c2 on u2.phone_no = c2.phone_no and c2.user_id=u1.id
where u1.id=1

我建议在contacts.phone_no上创建一个索引,并在users.phone_no上创建一个唯一索引以增强您的查询。

关于php - 连接两个表时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25403975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com