mysql - 有张订单表,假设有个2个手机号,每个手机号都有5个订单,如何用一个sql实现每个手机号随机取3个订单?
PHP中文网
PHP中文网 2017-04-17 14:43:54
0
1
680
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中文网

认证高级PHP讲师

reply all(1)
迷茫
(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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template