Complex sqlite query, what's the correct syntax?
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.
精彩评论