Home  >  Q&A  >  body text

mysql - 有张订单表,假设有个2个手机号,每个手机号都有5个订单,如何用一个sql实现每个手机号随机取3个订单?

CREATE TABLE `order` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `phone` bigint(20) NOT NULL DEFAULT '0' COMMENT '手机号',
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

有什么可以不用union all的方法吗,因为这个是我简化的模型,实际业务中,这个phone的数量可能很多。

SELECT
    phone,
    GROUP_CONCAT(order_id ORDER BY rand())
FROM
    `order`
WHERE
    phone IN (11, 22)
GROUP BY
    phone

上面这个方法还是取出了所有数据,GROUP_CONCAT函数不支持limit关键字。

PHP中文网PHP中文网2742 days ago639

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 14:45:54

    (SELECT `order_id` FROM `order` WHERE `phone`='$phone1' LIMIT 3 ORDER BY rand())
    UNION ALL
    (SELECT `order_id` FROM `order` WHERE `phone`='$phone2' LIMIT 3 ORDER BY rand())

    This is the simplest if only done with SQL, but the performance of ORDER BY rand() is very poor. The best thing is to take out a certain number of records and then randomly select three more in the program.

    reply
    0
  • Cancelreply