编写查询以获取Desired SQL表输出

时间:2014-07-30 09:44:02

标签: mysql sql sql-server

我有一些表,使用sql查询使用下表查找所需的输出。表格是:

EmpID   TabId
101   1
102   2
103   3
104   4
105   1

表名为Master

EmpID   Name
101   A1
102   A2
103   A3
104   A4
105   A5

表名为TableA

EmpID   Name
101   B1
102   B2
103   B3
104   B4
105   B5

表名为TableB

EmpID   Name
101   C1
102   C2
103   C3
104   C4
105   C5

表名为TableC

EmpID   Name
101   D1
102   D2
103   D3
104   D4
105   D5

表名为TableD

TabId   Name
1     TableA
2     TableB
3     TableC
4     TableD

表格名称AttMaster已提供给我们,所需的输出位于

之下
TabId   Name
101     A1
102     B2
103     C3
104     D4
105     A5

请帮助我如何使用sql查询获得所需的输出。我没有得到任何解决方案来找到输出。

2 个答案:

答案 0 :(得分:2)

这应该有效。希望它有所帮助

DECLARE @Master TABLE (EmpID INT, TabId INT)
DECLARE @TableA TABLE (EmpID INT, Name VARCHAR(10))
DECLARE @TableB TABLE (EmpID INT, Name VARCHAR(10))
DECLARE @TableC TABLE (EmpID INT, Name VARCHAR(10))
DECLARE @TableD TABLE (EmpID INT, Name VARCHAR(10))
DECLARE @AttMaster TABLE (TabId INT, Name VARCHAR(10))

INSERT INTO @Master VALUES
('101', '1'),
('102', '2'),
('103', '3'),
('104', '4'),
('105', '1')

INSERT INTO @TableA VALUES
('101', 'A1'),
('102', 'A2'),
('103', 'A3'),
('104', 'A4'),
('105', 'A5')

INSERT INTO @TableB VALUES
('101', 'B1'),
('102', 'B2'),
('103', 'B3'),
('104', 'B4'),
('105', 'B5')

INSERT INTO @TableC VALUES
('101', 'C1'),
('102', 'C2'),
('103', 'C3'),
('104', 'C4'),
('105', 'C5')

INSERT INTO @TableD VALUES
('101', 'D1'),
('102', 'D2'),
('103', 'D3'),
('104', 'D4'),
('105', 'D5')

INSERT INTO @AttMaster VALUES
('1', 'TableA'),
('2', 'TableB'),
('3', 'TableC'),
('4', 'TableD')


;WITH cte_MasterAttMaster AS
(
SELECT m.EmpID ,am.TabId, am.Name
FROM @Master m
JOIN @AttMaster am
on m.TabId = am.TabId
)
,cte_TableABCD(EmpID,Name,TName) AS
(
SELECT *,'TableA' FROM @TableA 
UNION ALL
SELECT *,'TableB' FROM @TableB 
UNION ALL
SELECT *,'TableC' FROM @TableC 
UNION ALL
SELECT *,'TableD' FROM @TableD
)
SELECT mam.EmpID,
      tb.Name
FROM cte_MasterAttMaster AS mam
    JOIN cte_TableABCD AS tb
    ON tb.EmpID = mam.EmpID
    AND tb.TName = mam.Name
ORDER BY mam.EmpID

答案 1 :(得分:0)

我敢肯定,这不是一个糟糕的问题 - 我认为这是糟糕的数据库设计。您可以使用UNION获得所需的结果。由于您更改了问题,更新了语句。每个SELECT将是一个连接:

SELECT      a.EmpId AS TabId, a.Name
FROM        TableA a
INNER JOIN  master m ON a.EmpId = m.EmpID
INNER JOIN  attMaster am ON m.TABId = am.EmpId
WHERE       am.Name = 'TableA'

UNION

SELECT      b.EmpId, b.Name
FROM        TableB b
INNER JOIN  master m ON b.EmpId = m.EmpID
INNER JOIN  attMaster am ON m.TABId = am.EmpId
WHERE       am.Name = 'TableB'

UNION

SELECT      c.EmpId, c.Name
FROM        TableC c
INNER JOIN  master m ON c.EmpId = m.EmpID
INNER JOIN  attMaster am ON m.TABId = am.EmpId
WHERE       am.Name = 'TableC'

UNION

SELECT      d.EmpId, d.Name
FROM        TableD d
INNER JOIN  master m ON d.EmpId = m.EmpID
INNER JOIN  attMaster am ON m.TABId = am.EmpId
WHERE       am.Name = 'TableD'

ORDER BY    TabId

DEMO (对于SQL Server 2008,但也适用于MySQL)。试试吧。