mySQL SELECT AS用于多个标准

时间:2013-10-06 23:01:48

标签: php mysql

我需要将这两个查询合并为1:

SELECT user1ID AS friendID FROM friends WHERE user2ID = '$userid'
UNION
SELECT user2ID AS friendID FROM friends WHERE user1ID = '$userid'

然后

SELECT firstName, lastName FROM users WHERE ID = friendID (that we just established)

1 个答案:

答案 0 :(得分:1)

我猜MySQL的UNIONManual)关键字正是您要找的。

由编辑问题编辑:

您需要一个子查询来处理您想要做的事情(JOIN也可能有用,但会更复杂):

SELECT firstName, lastName FROM users WHERE ID IN
(
    SELECT user1ID AS friendID FROM friends WHERE user2ID = '$userid'
    UNION
    SELECT user2ID AS friendID FROM friends WHERE user1ID = '$userid'
)

请注意,子查询可能会导致非常大的表和/或复杂查询中出现性能问题。在这种情况下,您可能希望将子查询重构为JOIN