繁体   English   中英

嵌套 SQL 从多个表和 COUNT 内联查询

[英]Nested SQL Query from multiple tables and COUNT inline

博主们好。

我想创建一个查询,它将 select car namemodelprice从表tblCars 在同一个查询结果中,我需要从表tblLikes中检查某个用户是否喜欢这辆车。 tblLikesiduserIdcarId (外键)。 因此,对于特定用户,我需要以下内容作为回报。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM