mysql select 2 row from each group by

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

i have 2 table with this structure

Products

 id       title ----------------- 1       sample 1 2       sample 2 3       sample 3 4       sample 4 5       sample 5 6       sample 6 

gallery

 id       typeid       name -------------------------------  1          1         sample for 1 2          1         sample for 1 3          1         sample for 1 4          2         sample for 2 5          2         sample for 2 7          2         sample for 2 8          3         sample for 3 9          3         sample for 3 10         3         sample for 3 11         4         sample for 4 12         4         sample for 4 13         5         sample for 5 14         5         sample for 5  

and iwant this for lists of id eg(1,2,3)

 id      typeid       name ---------------------  1      1          sample for 1 1      2          sample for 1 2      4          sample for 2 2      5          sample for 2 3      8          sample for 3 3      9          sample for 3 

here is my query

  select p.*,g.* from products p inner join gallery g ON p.id=g.typeid where p.id in (3,4,5) group by typeid 

here is real structure sqlfiddle link

回答1:

SELECT p.id, g.typeid, g.id, g.title FROM products p  INNER JOIN (SELECT * FROM gallery a             WHERE (SELECT COUNT(*) FROM gallery b WHERE b.title = a.title AND b.id >= a.id) <= 2            ) g ON p.id = g.typeid  WHERE p.id in (3,4,5) 

EDIT:

Try this SQL Fiddle Demo

SELECT p.id, g.typeid, g.id, g.name FROM products p  INNER JOIN (SELECT * FROM gallery a             WHERE (SELECT COUNT(*) FROM gallery b WHERE b.typeid = a.typeid AND b.id >= a.id) <= 2            ) g ON p.id = g.typeid  WHERE p.id in (3,4,5) order by g.id asc 

So basically this part

WHERE (SELECT COUNT(*) FROM gallery b WHERE b.title = a.title AND b.id >= a.id) <= 2 

is used to replace group by typeid



回答2:

SELECT p.id,p.title, g.typeid, g.id, g.name FROM products p  INNER JOIN (SELECT * FROM gallery a             WHERE (SELECT COUNT(*) FROM gallery b WHERE b.typeid = a.typeid AND b.id >= a.id) 

please try this



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!