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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘