请教sql多表联查的问题

有三个表,如下:
产品表goods:
gid,title,price
1 , 华为 , 4299
2 , Apple , 3299

用户表users:
uid,nickname,avatarUrl
1 , 小明 , 头像链接
2 , 小李 , 头像链接

出价表bids:
(status:0无效1有效,一个uid在同一个gid只能有一个有效价格)
id,uid,gid,price,status
1 , 1 , 1 , 2344 , 1
2 , 1 , 1 , 2345 , 0
2 , 1 , 1 , 1345 , 0

需求:查询所有商品,当前用户已出价的商品要显示当前有效出价并且显示对应昵称和头像,未参与出价的商品照常显示

请问该如何使用查询语句?

阅读 2.1k
2 个回答
select goods.title, goods.price, bids.price as 有效出价, users.nickname, users.avatarUrl
from goods,
     bids,
     users
where goods.gid = bids.gid
  and bids.status = 1
  and users.uid = bids.uid

union all

select title, price, null as 有效出价, null as nickname, null as avatarUrl
from goods
where gid not in (select gid from bids)
SELECT
    g.gid,
    g.title,
    g.price,
    u.nickname,
    u.avatarUrl,
    b.price bids_price 
FROM
    goods g
    LEFT JOIN bids b ON g.gid = b.gid AND b.STATUS = 1
    LEFT JOIN users u ON b.uid = u.uid 
  ORDER BYb.STATUS DESC;

你试试这个,是不是你想要的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题