MySql 子查询返回超过 1 行

发布于 2024-10-29 02:39:49 字数 926 浏览 1 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

转瞬即逝 2024-11-05 02:39:49

我会通过 JOIN 来完成。

SELECT fr.name FROM Person fr INNER JOIN Friendship ON(fr.pid = Friendship.pid2) INNER JOIN Person p ON(Friendship.pid = p.pid) WHERE p.name = 'Marie';

不过,您也可以通过 JOIN 和子选择来完成此操作。

SELECT name FROM Person INNER JOIN Friendship ON(Person.pid = Friendship.pid2) WHERE Friendship.pid IN (SELECT pid FROM Person WHERE name = 'Marie'); 

I would do it through a JOIN.

SELECT fr.name FROM Person fr INNER JOIN Friendship ON(fr.pid = Friendship.pid2) INNER JOIN Person p ON(Friendship.pid = p.pid) WHERE p.name = 'Marie';

You could also do this through a JOIN and a subselect though.

SELECT name FROM Person INNER JOIN Friendship ON(Person.pid = Friendship.pid2) WHERE Friendship.pid IN (SELECT pid FROM Person WHERE name = 'Marie'); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文