对于订购商品订单超过1件的订单,最多只能选择2行

时间:2017-02-28 09:44:32

标签: mysql sql database mysqli

enter image description here

我想显示所有超过1件商品的订单,但如果商品超过2件商品只显示2行

enter image description here

如果您有任何想法,我将不胜感激,谢谢。

3 个答案:

答案 0 :(得分:2)

每个id都有一个行号列,这极大地简化了查询。在这种情况下,我们只需将ORDERS表连接到子查询即可得出您的预期输出,该子查询标识id有2个或更多与之关联的记录。

SELECT t1.*
FROM ORDERS t1
INNER JOIN
(
    SELECT id
    FROM ORDERS
    GROUP BY id
    HAVING COUNT(*) >= 2
) t2
    ON t1.id = t2.id
WHERE t1.rown_num <= 2

答案 1 :(得分:1)

尝试这个简单的解决方案

SELECT * FROM orders od WHERE od.id IN( SELECT id FROM orders o GROUP BY o.id HAVING o.id HAVING COUNT(o.id)>1)

答案 2 :(得分:0)

试试这个: 第一个连接将为您提供所需的行,第二个连接将添加rown_num字段

  select a.id,
           a.item_num,
           b.rown_num
    from
    (select id,
           item_num
    from orders 
    where rown_num in (1,2)
    group by id,item_num
    having count(id)>=2)a
    inner join (select *
                 from orders )b on a.id=b.id
                               and a.item_num=b.item_num