MySql 子查询返回超过 1 行
我在 mysql 查询自我多对多关系时遇到一些问题 我有一个 Person 表和一个 Friendship 表
Person
PID |名称 |年龄
1 吉米 18
2 卢卡斯 25
3 玛丽 12
4 玛丽 40
约翰福音 5 章 30
友谊
PID | pId2
1 3
2 3
4 1
5 3
所以我需要
通过下面的查询检查玛丽的朋友(正确答案:卢卡斯和约翰),我通过 pid 得到了答案,
SELECT p.name
FROM Person p
WHERE EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid
AND (f.pid2 = 4 OR f.pid2 = 3))
OR EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid2
AND (f.pid = 4 OR f.pid = 3))
但是如果我需要按名字查询怎么办?下面的这个不起作用,
SELECT p.name
FROM Person p
WHERE EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid
AND f.pid2 = (SELECT pid FROM Person WHERE name = 'Marie'))
OR EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid2
AND f.pid = (SELECT pid FROM Person WHERE name = 'Marie'))
谢谢你们的帮助
im having some problems to query at mysql a self many to many relationship
i got a Person table and a Friendship table
Person
pid | name | age
1 Jimmy 18
2 Lucas 25
3 Marie 12
4 Marie 40
5 John 30
Friendship
pid | pId2
1 3
2 3
4 1
5 3
So i need to check whats Marie's friends (correct answer: Lucas and John )
with the follow query i got the answer by the pid
SELECT p.name
FROM Person p
WHERE EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid
AND (f.pid2 = 4 OR f.pid2 = 3))
OR EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid2
AND (f.pid = 4 OR f.pid = 3))
but what if i need to query by the name?the follow one doesnt work
SELECT p.name
FROM Person p
WHERE EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid
AND f.pid2 = (SELECT pid FROM Person WHERE name = 'Marie'))
OR EXISTS(SELECT NULL
FROM Friendship f
WHERE p.pid = f.pid2
AND f.pid = (SELECT pid FROM Person WHERE name = 'Marie'))
thanks for your help guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会通过 JOIN 来完成。
不过,您也可以通过 JOIN 和子选择来完成此操作。
I would do it through a JOIN.
You could also do this through a JOIN and a subselect though.