SQL Server sqlserver multi-table query

mkshixfv  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(119)

I have 4 tables with foreign key constraints between them. At present, I only know the username of the first table users. I want to get the quantity field in the third table and the gname field in the 4th table. The database structure is as follows,thank you!

My idea is to divide the query into two steps, first query the gid and quantity fields in the cartitem table, save the data, and then query gname according to gid. It feels a little troublesome.

select
  gname
from goods
where goods.gid in (
    select gid
    from cartitem
    where cartid = (
        select cartid
        from cart
        where userid = (
            select userid
            from users
            where name = 'admin'
        )
    )
);
kwvwclae

kwvwclae1#

In your case using subquery might be a bit tedious, consider using join

Here is my solution using join

select ci.quantity, gd.gname 
        from users u    
           join cart c on u.userid = c.userid   
           join cartitem ci on c.cartid = ci.cartid 
           join goods gd on ci.gid = gd.gid
         where u.name = 'admin'

相关问题