mysql语法连接两个字段

时间:2012-07-31 18:18:21

标签: mysql join

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

如果我在第一个表格中的任何一个字段上匹配,第二个表格中只有一些我想要提取的其他信息。

表网络

id | inviter | invitee | status

表userinfo

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'"

非常感谢任何建议。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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';