我有以下两个表:
users: id | nickname | phone
phonebook: id | ownerid | phone | name
昵称和手机都是索引和varchars,ownerid也是索引。
表电话簿包含给定用户的联系人列表,即:1, 1, '+12345678','Jimmy'
我所需要的只是查找所有位于ownerId电话簿中的用户昵称。
我试过以下:SELECT u.nickname FROM users u WHERE u.phone IN (SELECT pb.phone FROM phonebook pb WHERE pb.ownerid=1)
但它总是返回空集。
示例数据
users
1 | josh | +380123456789
2 | jimmy | +12345678
3 | vladimir | +421987123456
phonebook
1 | 1 | +12345678 | Jimmy Surname
2 | 1 | +12567321 | Anne (This user isn't registered in this service / users)
3 | 1 | +421987123456 | Vladimir Novak
4 | 3 | +3556233455 | Julia
所以基本上我需要返回jimmy,vladimir
,因为它们存在于用户1(ownerid=1
)的电话簿和用户表中。
答案 0 :(得分:2)
您想要从用户中选择昵称:
select nickname
from users
您只想选择电话号码在用户1的朋友组中的记录:
where phone in
(
select phone
from phonebook
where ownerid = 1
)
组合:
select nickname
from users
where phone in
(
select phone
from phonebook
where ownerid = 1
);