SQL选择多个引用单表

时间:2010-08-10 18:24:31

标签: sql database

我有一个包含多个关系表的SQL DB。主表中有一些字段多次引用另一个表。例如,假设我有一个负责多个州销售的销售人员数据库。我的数据库包含State1,State2和State3的字段,所有字段都映射回States表。我无法弄清楚如何编写查询以返回具有所有枚举状态的记录。如果我只需要一个州立场,我知道我会这样做:

SELECT Master.Name, State.Enumeration AS 'State'
FROM MasterTable Master, StateTable State
WHERE Master.State1 = State.ID;

如何为所有州字段展开此内容?

感谢。

3 个答案:

答案 0 :(得分:11)

将每个唯一联接的列返回到状态:

select m.Name, s1.Enumeration as State1, s2.Enumeration as State2, s3.Enumeration as State3
from MasterTable m
left join StateTable s1 on m.State1 = s1.ID
left join StateTable s2 on m.State2 = s2.ID
left join StateTable s3 on m.State3 = s3.ID

从3个连接中返回所有状态的1列:

select m.Name, ISNULL(s1.Enumeration + ',','') 
               + ISNULL(s2.Enumeration + ',','') 
               + ISNULL(s3.Enumeration,'') as Enumeration
from MasterTable m
left join StateTable s1 on m.State1 = s1.ID
left join StateTable s2 on m.State2 = s2.ID
left join StateTable s3 on m.State3 = s3.ID

还有列查询...

select m.Name,
 ISNULL((select Enumeration from StateTable where ID = m.State1),'') as State1,
 ISNULL((select Enumeration from StateTable where ID = m.State2),'') as State2,
 ISNULL((select Enumeration from StateTable where ID = m.State3),'') as State3
from MasterTable m

答案 1 :(得分:6)

您需要使用表别名才能连接同一个表的多个副本:

   SELECT m.Name, 
          s1.Enumeration AS 'State1',
          s2.Enumeration AS 'State2'
     FROM MasterTable m
LEFT JOIN StateTable s1 = s1.id = m.state1
LEFT JOIN StateTable s2 = s1.id = m.state2

INNER JOIN要求存在数据 - 如果不存在,则排除整个记录。 LEFT JOIN更安全,就像state1 / 2/3 / etc允许NULL ...

一样

答案 2 :(得分:0)

select tbl_book_con1.city,con1,tbl_book_destination.city,destination,labar_char,tbl_book_c_from.city,c_from,tbl_book_c_to.city,c_to,tbl_book_payment.city,paymentid from tbl_booking tbb_bookinner join tbl_master tbl_book_con1 on tbl_book_con1.id = tbb_book.con1
inner join tbl_master tbl_book_destination on tbl_book_destination.id = tbb_book.con1
inner join tbl_master tbl_book_c_from on tbl_book_c_from.id = tbb_book.con1
inner join tbl_master tbl_book_c_to on tbl_book_c_to.id = tbb_book.con1
inner join tbl_master tbl_book_payment on tbl_book_payment.id = tbb_book.con1

enter image description here