开发者

MySql Subquery returns more than 1 row

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


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'); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜