跪left join 的sql语句写法

WBOY
Release: 2016-06-13 13:11:09
Original
1695 people have browsed it

跪求一个left join 的sql语句写法
表goods: gid | name 
  1 xde
  2 dfdd
  3 东方古国风格
表glist: lid | gid | subname | displayorder
  1 1 三三四四 2
  2 1 扫扫地 12  
  3 2 日方非法 10
  4 2 到噶多个 1
我现在想取出glist表中的lid为2,3两项。
但是SELECT g . * , f . * FROM goods g LEFT JOIN glist f ON g.gid = f.gid ORDER BY g.displayorder DESC limit 2 这个sql取出的结果是错误的。

按照goods中的gid升序 取出两条 同时也取出在glist中属于相应gid的一条(取displayorder值最大的一个)
结果应为goods中的1,2 同时也取出glist中的2,3

------解决方案--------------------
可以这么写select a.*,max(b.displayorder),b.subname from goods as a left join glist as b on a.gid=b.gid group by a.gid
分组查询displayorder字段最大值
------解决方案--------------------
SELECT g . * , f . * FROM goods g LEFT JOIN glist f ON g.gid = f.gid ORDER BY f.displayorder DESC limit 2

你的sql有问题,不是g,是f。但是这样不能满足你以下要求
“按照goods中的gid升序 取出两条 同时也取出在glist中属于相应gid的一条(取displayorder值最大的一个)
结果应为goods中的1,2 同时也取出glist中的2,3”

楼上也是错的,虽然max(b.displayorder)取出来是对的,但是b.subname不对。

正确的应该是:
select * from (select g.gid, g.name, f.lid,f.subname,f.displayorder from goods g left join glist f on g.gid=f.gid order by g.gid ASC, f.displayorder DESC) h group by h.gid LIMIT 2

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!