douwen9540 2016-07-11 05:20
浏览 17

SQL从表中选择匹配最低ID的所有行

I have table like so:

    id  |  order_id  |  product_id
------------------------------------
    1   |  356       |  80
    2   |  356       |  81
    3   |  357       |  77
    4   |  357       |  80
    5   |  357       |  78
    6   |  358       |  90

What I would like to be able to do is to grab the 2 lowest order_id values without knowing how many there are to begin with, but I am having trouble thinking of how to create the query to select these rows...

SELECT * FROM table ORDER BY order_id ASC

Is there a way to do this within MySQL, that will always return the lowest order_id value rows, so in this case, I should get the first 2 rows returned. If the first 2 rows didn't exist, than I should get returned rows 3 - 5 (totaling 3 rows for order id 357).

How to do this?

  • 写回答

3条回答 默认 最新

  • doushijiao0679 2016-07-11 05:25
    关注

    Please try this:


    SELECT 
    *
    FROM 
    table INNER JOIN 
    (
        SELECT MIN(order_id) AS min_order_id
        FROM table
    ) AS t
    ON t.order_id = table.order_id;
    
    • First get the minimum order id and give it an alias t.
    • Now Make an inner join between your table and this alias t ON order_id.
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀