我有三张表Chain,Hotel和Shell。酒店表链接与链表和贝壳表链接与两个表。
表结构:---
链 //第2级
ChainID | ChainName
酒店 //等级3
HotelID | HotelName | ChainID
贝壳
ShellID | ShellName | Chain_Hotel_ID | Level
在Shell表中,Chain_Hotel_ID列保留(Chain和Hotel)表ChainID和HotelID和Level Column Hold Int Value 2和3. Chain考虑为2和Hotel 3
从这些表中我想要
ShellID | ShellName | ChainName
我为此编写了一个查询,但它没有按我的意愿工作
select
_gs.ShellID, _gs.ShellName, _gc.ChainName
from
Shell _gs, Chain _gc
where
_gc.ChainID in (select _lh.ChainID
from Shell _ls,Hotel _lh
where _lh.HotelID = _ls.Chain_Hotel_ID and _ls.Level = 3)
and _gs.Level = 3
样本表数据
链
ChainID | ChainName
1 | Sarovar
2 | Taj Group
3 | Oberoi
饭店
HotelID | HotelName | ChainID
1 | RadhaRegent | 1
2 | SarovarPortic | 1
3 | LaxmiVilas | 1
4 | Taj Mumbai | 2
5 | Taj Delhi | 2
6 | Oberoi Delhi | 3
壳牌
ShellID | ShellName | Chain_Hotel_ID | Level
1 | Shell1 | 1 | 2
2 | Shell2 | 1 | 2
3 | Shell3 | 2 | 3
4 | Shell4 | 3 | 2
5 | Shell5 | 2 | 3
6 | Shell6 | 3 | 3
7 | Shell7 | 4 | 3
输出
ShellID | ShellName | ChainName
3 | Shell3 | Sarovar
5 | Shell5 | Sarovar
6 | Shell6 | Sarovar
7 | Shell7 | Taj Group
3 | Shell3 | Sarovar
5 | Shell5 | Sarovar
6 | Shell6 | Sarovar
7 | Shell7 | Taj Group
我得到了重复的数据
答案 0 :(得分:2)
这是你需要的吗?
IF LEVEL=3
BEGIN
SELECT DISTINCT ShellID, ShellName, ChainName
FROM HOTEL JOIN SHELL
ON HOTEL.CHAINID=SHELL.CHAIN_HOTEL_ID
JOIN
CHAIN ON CHAIN.CHAINID=HOTEL.CHAINID
END
答案 1 :(得分:0)
您只需按给定顺序连接表:Shell - >酒店 - >链。
以下是代码示例:
SELECT
s.Id AS ShellID, s.Name AS ShellName, c.Name AS ChainName
FROM #shell s
INNER JOIN #hotel h ON h.Id = s.HotelId
INNER JOIN #chain c ON c.Id = h.ChainID
WHERE s.Level = 3
要测试的完整列表:
CREATE TABLE #chain (Id INT, Name varchar(50))
GO
INSERT INTO #chain VALUES (1, 'Sarovar'), (2, 'Taj Group'), (3, 'Oberoi')
GO
CREATE TABLE #hotel (Id INT, Name varchar(50), ChainId INT)
GO
INSERT INTO #hotel VALUES
(1, 'RadhaRegent' , 1),
(2, 'SarovarPortic' , 1),
(3, 'LaxmiVilas' , 1),
(4, 'Taj Mumbai' , 2),
(5, 'Taj Delhi' , 2),
(6, 'Oberoi Delhi' , 3)
GO
CREATE TABLE #shell (Id INT, Name varchar(50), HotelId INT, Level INT)
GO
INSERT INTO #shell VALUES
(1, 'Shell1', 1, 2),
(2, 'Shell2', 1, 2),
(3, 'Shell3', 2, 3),
(4, 'Shell4', 3, 2),
(5, 'Shell5', 2, 3),
(6, 'Shell6', 3, 3),
(7, 'Shell7', 4, 3)
GO
SELECT
s.Id AS ShellID, s.Name AS ShellName, c.Name AS ChainName
FROM #shell s
INNER JOIN #hotel h ON h.Id = s.HotelId
INNER JOIN #chain c ON c.Id = h.ChainID
WHERE s.Level = 3
DROP TABLE #chain;
GO
DROP TABLE #hotel;
GO
DROP TABLE #shell;
GO