根据主表中的外键选择外键表(表B)中的非ID列(TABLE

时间:2014-06-24 07:14:10

标签: sql sql-server database

我有两张桌子,一张STUDENT和RULES表。学生表包含与学生相关的数据,规则表包含与特定学生相关的规则。 现在在学生表上,我有5列作为规则表的外键,例如

CREATE TABLE dbo.RULES
(
    ID int identity not null primary key,
    RULENAME varchar
)

CREATE TABLE dbo.STUDENT
(
    ID int identity not null primary key,
    NAME varchar(50),
    SURNAME varchar(50),
    ADRESS varchar(50),
    RULE1 int not null references dbo.RULES(ID),
    RULE2 int not null references dbo.RULES(ID),
    RULE3 int not null references dbo.RULES(ID),
    RULE4 int not null references dbo.RULES(ID),
    RULE5 int not null references dbo.RULES(ID)
)

我想要实现的是从学生表中选择NAME,SURNAME,ADDRESS并将其与RULENAME一起加入STUDENT中的每个RULE外键,例如

NAME SURNAME ADDRESS RULE1NAME RULE2NAME RULE3NAME RULE4NAME RULE5NAME

我熬夜试图解决这个问题,但遗憾的是我仍然在方方面面。我会将这归因于我在SQL方面缺乏经验,但是,有人可以帮助我吗?

更新

感谢你们的回答家伙,dotnetom,Bharadwaj。

我内心加入了5次,就像dotnetoms的回答一样。查询工作正常但它返回所有五个规则的相同规则。这是我的查询

SELECT 
STUDENT.NAME, 
STUDENT.SURNAME, 
STUDENT.ADDRESS, 
RULES.RULENAME AS RULE1NAME, 
RULES.RULENAME AS RULE2NAME, 
RULES.RULENAME AS RULE3NAME, 
RULES.RULENAME AS RULE4NAME, 
RULES.RULENAME AS RULE5NAME
FROM STUDENT s 
INNER JOIN RULES AS r1 ON STUDENT.RULE1 = RULES.ID
INNER JOIN RULES AS r2 ON STUDENT.RULE2 = RULES.ID
INNER JOIN RULES AS r3 ON STUDENT.RULE3 = RULES.ID
INNER JOIN RULES AS r4 ON STUDENT.RULE4 = RULES.ID
INNER JOIN RULES AS r5 ON STUDENT.RULE5 = RULES.ID

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您应该可以使用此查询:

SELECT 
    s.NAME, 
    s.SURNAME, 
    s.ADDRESS, 
    r1.RULENAME AS RULE1NAME, 
    r2.RULENAME AS RULE2NAME, 
    r3.RULENAME AS RULE3NAME, 
    r4.RULENAME AS RULE4NAME, 
    r5.RULENAME AS RULE5NAME
FROM STUDENT s 
    INNER JOIN RULES r1 ON s.RULE1 = r1.ID
    INNER JOIN RULES r2 ON s.RULE2 = r2.ID
    INNER JOIN RULES r3 ON s.RULE3 = r3.ID
    INNER JOIN RULES r4 ON s.RULE4 = r4.ID
    INNER JOIN RULES r5 ON s.RULE5 = r5.ID