在左加入时,我对这些事情提出了一些问题。
我有这些表格:
dbo.ARoom_type
id | roomtype_name | isactive
---+---------------+-----------
1 | Presidential | 1
2 | De Luxe | 1
dbo.AAmenities
id | amenities_name | isactive
---+----------------+----------
1 | Internet | 1
2 | Cable TV | 1
3 | Bath Tub | 1
4 | Air-con | 1
5 | Telephone | 1
dbo.AAmenities_details:
id | roomtype_id | amenities_id
---+-------------+--------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 4
4 | 2 | 1
我试过了这个查询
SELECT
B.id as 'details_id',
C.roomtype_name,
A.amenities_name
FROM
AAmenities AS A
LEFT JOIN
AAmenities_details AS B ON B.amenities_id = A.id
LEFT JOIN
ARoom_type as C ON C.id = B.roomtype_id
这就是我得到的
结果:
details_id | roomtype_name | amenities_name
-----------+----------------+----------------
1 | Presidential | Internet
2 | De Luxe | Internet
3 | Presidential | Cable TV
4 | NULL | Bath Tub
5 | Presidential | Air-con
6 | NULL | Telephone
我可以获得所有的便利设施,并获得所有的房型名称,这是我想要的但我希望这是房型,所以如果总统只有总统和我试过这个查询
@id INT
AS
BEGIN TRY
SELECT
B.id AS 'details_id',
C.roomtype_name,
A.amenities_name
FROM
AAmenities AS A
LEFT JOIN
AAmenities_details AS B ON B.amenities_id = A.id
LEFT JOIN
ARoom_type AS C ON C.id = B.roomtype_id
WHERE
C.id = @id
我只能得到这些结果
id | roomtype_name | amenities_name
----+-----------------+----------------
1 | Presidential | Internet
2 | Presidential | Cable TV
4 | Presidential | Air-con
这是结果,当我想要的是它会是这样的:
details_id | roomtype_name | amenities_name
-----------+----------------+-----------------
1 | Presidential | Internet
3 | Presidential | Cable TV
4 | NULL | Bath Tub
5 | Presidential | Air-con
6 | NULL | Telephone
什么是正确的查询,当我想要id并仍然得到所有的amenities_name,即使我的roomtype_name的值为NULL,如何LEFT JOIN答案?非常感谢你
答案 0 :(得分:0)
您需要AAmenities_details
的所有数据,然后尝试
SELECT
B.id as 'details_id',
C.roomtype_name,
A.amenities_name
FROM
AAmenities_details as B
LEFT JOIN AAmenities as A
on B.amenities_id = A.id
LEFT JOIN ARoom_type as C
on C.id = B.roomtype_id
WHERE B.roomtype_id = @id
但我认为每个AAmenities_details
都必须有AAmenities
因此,您可以在INNER JOIN
和AAmenities_details
AAmenities
SELECT
B.id as 'details_id',
C.roomtype_name,
A.amenities_name
FROM
AAmenities_details as B
INNER JOIN AAmenities as A
on B.amenities_id = A.id
LEFT JOIN ARoom_type as C
on C.id = B.roomtype_id
WHERE B.roomtype_id = @id