您的语法几乎是正确的,只是您不希望在表与其别名之间使用逗号a
或u
(可选地使用AS
关键字),并且您需要第二次加入,userinfo
因为您需要邀请者和被邀请者的不同数据:
SELECT
/* Use column aliases to distinguish inviter/invitee details */
n.id AS n_id,
n.status,
inviter.userid AS inviter_userid,
inviter.name AS inviter_name,
invitee.userid AS invitee_userid,
invitee.name AS invitee_name
FROM
network AS n
/* JOIN against `userinfo` twice: once to get inviter, once for invitee */
/* aliased as inviter/invitee */
LEFT JOIN userinfo AS inviter ON n.inviter = inviter.userid
LEFT JOIN userinfo AS invitee ON n.invitee = invitee.userid
WHERE
n.inviter = 22
OR n.invitee = 22
更新:
要仅返回匹配的其中一个或另一个,您可以使用语句对其进行修改,以确定它们中的哪一个与子句CASE
中的值相同:WHERE
SELECT
/* Use column aliases to distinguish inviter/invitee details */
n.id AS n_id,
n.status,
/* Return only one name, whichever matches the same value as in WHERE */
CASE
WHEN inviter.userid = 22 THEN inviter.name
WHEN invitee.userid = 22 THEN invitee.name
END AS name
FROM
network AS n
/* JOIN against `userinfo` twice: once to get inviter, once for invitee */
/* aliased as inviter/invitee */
LEFT JOIN userinfo AS inviter ON n.inviter = inviter.userid
LEFT JOIN userinfo AS invitee ON n.invitee = invitee.userid
WHERE
n.inviter = 22
OR n.invitee = 22
更新 2:
好吧,仔细想想,如果你只需要你已经知道的 id 的名称(22),就不需要 2 个连接。您仍然需要CASE
在子查询中使用,但它只需要返回 id。
SELECT
n.*,
u.*
FROM (
SELECT
id AS n_id,
status,
CASE
WHEN inviter = 22 THEN inviter
WHEN invitee = 22 THEN invitee
END AS i_id
FROM network
WHERE inviter = 22 OR invitee = 22
) n JOIN userinfo u ON n.i_id = userinfo.userid