0

我想将一个表连接到另一个表,其中第一个表中的两个字段中的任何一个都是第二个表的键。

如果我在第一个表中的任何一个字段上得到匹配,第二个表只是有一些我想提取的附加信息。

表网络

id | inviter | invitee | status

表用户信息

id | userid | name

查询是否没有访问第二个表

"SELECT * from network where inviter= '22' OR invitee ='22'"

我认为它类似于以下内容,但无法弄清楚语法:

"SELECT n.*,u.* from `network`, n
left join `users`, u on
n.inviter = u.id OR n.invitee= u.id
WHERE n.inviter = '22' or n.invitee= '22'"

非常感谢您的任何建议。

4

2 回答 2

1

您的语法几乎是正确的,只是您不希望在表与其别名之间使用逗号au(可选地使用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
于 2012-07-31T18:22:33.090 回答
0

尝试这个:

SELECT a.inviter, a.invitee, a.status,b.userid, b.name FROM network a INNER JOIN userinfo b ON a.id = '22' AND b.id = '22';

要使用多个键进行连接,请尝试以下操作:

SELECT SELECT a.inviter, a.invitee, a.status,b.userid, b.name FROM network a INNER JOIN userinfo b ON a.invitee = '22' AND b.userid = '22' OR a.inviter = '22' AND b.userid ='22';
于 2012-07-31T18:20:13.567 回答