从两个不同的表中选择

时间:2011-08-08 05:40:55

标签: sql

所以,我有两个表,表R和表N.表R中的数据来自表N.我的问题是我不知道将显示结果的SELECT查询如下,因为有4个名称和SQL只能选择1.是否有查询或任何其他方式来获得结果?

Table R:
Id1 Id2 Id3 Id4
1   3   5   7
2   4   6   8

Table N:
Id  Name
1   A
2   B
3   C
4   D
5   E
6   F
7   G
8   H

在SELECT语句之后,结果应如下所示:

Name1   Name2   Name3   Name4
A       C       E       G
B       D       F       H

无论如何,谢谢你的帮助。 ^ _ ^

3 个答案:

答案 0 :(得分:3)

SELECT
  N1.Name AS `Name1`,
  N2.Name AS `Name2`,
  N3.Name AS `Name3`,
  N4.Name AS `Name4`
FROM
  R
INNER JOIN
  N N1
ON
  N1.Id = R.Id1
INNER JOIN
  N N2
ON
  N2.Id = R.Id2
INNER JOIN
  N N3
ON
  N3.Id = R.Id3
INNER JOIN
  N N4
ON
  N4.Id = R.Id4

答案 1 :(得分:0)

select
  n1.Name as Name1,
  n2.Name as Name2,
  n3.Name as Name3,
  n4.Name as Name4
from
  R
  inner join N n1 on n1.id = R.id1
  inner join N n2 on n2.id = R.id2
  inner join N n3 on n3.id = R.id3
  inner join N n4 on n4.id = R.id4

答案 2 :(得分:0)

  1. 您可以在查询中重命名该表
  2. 如果您重命名,可以多次加入同一个表,所以:

    select N1.Name, N2.Name, N3.Name, N4.Name
    from R
    join N as N1 on N1.Id = Id1
    join N as N2 on N2.Id = Id2
    join N as N3 on N3.Id = Id3
    join N as N4 on N4.Id = Id4
    

    (当然这相当于

    select N1.Name, N2.Name, N3.Name, N4.Name
    from R, N as N1, N as N2, N as N3, N as N4
    where N1.Id = Id1 and
        N2.Id = Id2 and
        N3.Id = Id3 and
        N4.Id = Id4
    

    (on子句只添加到where和逗号加入)