开发者

Complex sqlite query, what's the correct syntax?

开发者 https://www.devze.com 2023-04-05 05:59 出处:网络
The query is this one: SELECT FriendID FROM Relationships WHERE UserID = 1 INTERSECT (SELECT FriendID FROM Relationships WHERE UserID = 2

The query is this one:

SELECT FriendID FROM Relationships WHERE UserID = 1
INTERSECT
   (SELECT FriendID FROM Relationships WHERE UserID = 2
    UNION SELECT UserID FROM Relationships WHERE FriendID = 2)

(for the curious readers, please note that the friend relationship is not necessarily symmetrical in this scenario)

I've tried all the possible combination of parentheses with no luck.

If I omit the parentheses, there's no operator precedence开发者_如何学Go in the sense that it reads it like 5+6*3 = 33, so if I put the union before the intersection, the query works fine. But what will I do when I will have to intersect two unions?


You can use temporary tables in such case.


Thanks to Larry Lustig (which pointed me this), I rewrote my query as follows

SELECT FriendID FROM Relationships WHERE UserID = 1
INTERSECT SELECT ID FROM
   (SELECT FriendID AS ID FROM Relationships WHERE UserID = 2
    UNION SELECT UserID AS ID FROM Relationships WHERE FriendID = 2)

And it works.

0

精彩评论

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