I am joining between 3 tables and getting the wrong result. The goal is to list ALL the restaurants in the restaurants table and display the rating for any restaurant if the rating exists, otherwise display null, and only for ratings for burger.
This is the SQL:
SELECT r.RestaurantID, RestaurantName, cr.Rating FROM Restaurant r
LEFT JOIN CustRating cr ON cr.RestaurantID = r.RestaurantID
LEFT JOIN FoodType ft ON ft.FoodTypeID = cr.FoodTypeID AND
ft.FoodTypeName = 'Burger'
This is the result:

However ‘Cafe C’ should have Rating = null because I only want to display ratings for Burgers. What’s the proper SQL?
The SQL Statements to create the tables and populate with data:
CREATE TABLE [dbo].[Restaurant](
[RestaurantID] [int] NOT NULL,
[RestaurantName] [varchar](250) NOT NULL
)
CREATE TABLE [dbo].[FoodType](
[FoodTypeID] [int] NOT NULL,
[FoodTypeName] [varchar](50) NOT NULL
)
CREATE TABLE [dbo].[CustRating](
[RestaurantID] [int] NOT NULL,
[FoodTypeID] [int] NOT NULL,
[Rating] [smallint] NOT NULL
)
BEGIN TRANSACTION;
INSERT INTO [dbo].[CustRating]([RestaurantID], [FoodTypeID], [Rating])
SELECT 2, 1, 3 UNION ALL
SELECT 3, 2, 2
COMMIT;
GO
BEGIN TRANSACTION;
INSERT INTO [dbo].[FoodType]([FoodTypeID], [FoodTypeName])
SELECT 1, N'Burger' UNION ALL
SELECT 2, N'Taco'
COMMIT;
GO
BEGIN TRANSACTION;
INSERT INTO [dbo].[Restaurant]([RestaurantID], [RestaurantName])
SELECT 1, N'Cafe A' UNION ALL
SELECT 2, N'Cafe B' UNION ALL
SELECT 3, N'Cafe C'
COMMIT;
GO
1 Answer