[英]Nested SQL Query from multiple tables and COUNT inline
博主們好。
我想創建一個查詢,它將 select car name
, model
, price
從表tblCars
。 在同一個查詢結果中,我需要從表tblLikes
中檢查某個用戶是否喜歡這輛車。 tblLikes
有id
、 userId
和carId
(外鍵)。 因此,對於特定用戶,我需要以下內容作為回報。
1 Corolla Toyota R100,000 1 (user liked)
2 A3 Audi R700,000 0 (user did not like)
我嘗試過的是以下沒有成功。
SELECT
CarName
, CarModel
, CarPrice
, (
SELECT COUNT(*)
FROM tblLikes
WHERE
userId = @userId
AND CarId = @CarID
) as Likes
FROM tblCars
SELECT COUNT(*)
FROM tblLikes
WHERE
userId = @userId
AND CarId = @CarID
如果記錄存在則返回1
,如果不存在則返回0
。
declare @tblCars table (
id int IDENTITY(1,1) NOT NULL
, CarName varchar(20)
, CarModel varchar(20)
, CarPrice money
)
declare @tblLikes table (
id int IDENTITY(1,1) NOT NULL
, userId int
, carId int
)
insert into @tblCars (
CarName
, CarModel
, CarPrice
)
select 'BMW' , 'qqq', '1000'
union all select 'Mercedes' , 'www', '2000'
union all select 'Audi' , 'eee', '3000'
union all select 'Scania' , 'rrr', '4000'
union all select 'Opel' , 'ttt', '5000'
union all select 'Mazda' , 'yyy', '6000'
union all select 'Budatti' , 'uuu', '7000'
union all select 'Lamborgini' , 'iii', '8000'
union all select 'Tesla' , 'ooo', '9000'
union all select 'Space' , 'ppp', '10000'
insert into @tblLikes (
userId
, carId
)
select '1', '1'
union all select '1', '3'
union all select '1', '5'
union all select '1', '7'
union all select '1', '9'
select
c.*
, (
case when l.id is not null
then '1'
else '0'
end
) as likes
from @tblCars as c
left outer join @tblLikes as l
on l.carId = c.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.