dongsu0308 2013-05-01 16:40
浏览 172
已采纳

如何使用MySQL Group选择多个记录?

I can't seem to use distinct or group by to group certain mySQL records together. This SQL query below just returns one line each - I want all the values in the CID though..

I want to select a random group by cid or the first set in the table.. I cant use AND CID=X .. is there a way to do it without ..

Table

id      pid     image                           sort_order      cid
-----
2474    50      data/low.jpg            2                       56
2473    50      data/hi.jpg             3                       59
2471    50      data/thumn.jpg      500                     59
2472    50      data/front.jpg      1000                    56
2470    50      data/back.jpg           1                       56

Query

SELECT *
FROM `ocm1__product_image`
WHERE `product_id` = '50'
GROUP BY `cid`
ORDER BY `ocm1__product_image`.`sort_order` ASC
LIMIT 0 , 30

This should return

id      pid     image                           sort_order      cid
2474    50      data/low.jpg            2                       56
2472    50      data/front.jpg      1000                    56
2470    50      data/back.jpg           1                       56

But it returns both colours.. can I not unique the group?

It returns this which is wrong, I want to list all cid unique values

id      pid     image                           sort_order      cid
2474    50      data/low.jpg            2                       56
2471    50      data/thumn.jpg      500                     59
  • 写回答

2条回答 默认 最新

  • douren5490 2013-05-01 17:17
    关注

    This will return all the entries with the lowest cid for the requested pid.
    It gives the same result as you say that you need, without giving a specific cid as a condition;

    SELECT o1.*
    FROM `ocm1__product_image` o1
    LEFT JOIN `ocm1__product_image` o2
      ON o1.pid=o2.pid AND o1.cid > o2.cid
    WHERE o1.`pid` = '50' AND o2.cid IS NULL
    ORDER BY `o1`.`sort_order` ASC
    LIMIT 0 , 30
    

    An SQLfiddle to test with.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档