INSERT INTO `alsobuy_order_item` (`person`,`product_id`,`times`) SELECT * FROM ( ( SELECT CONVERT(o.customer_id,CHAR) AS `person`, oi.product_id, FLOOR(UNIX_TIMESTAMP(DATE_FORMAT(o.created_at,'%Y-%m-%d %H:00:00'))/(3600*1)) AS `time` FROM `sales_flat_order` AS o LEFT OUTER JOIN `sales_flat_order_item` AS oi ON o.entity_id = oi.order_id WHERE NOT o.customer_id IS NULL AND o.status='complete' GROUP BY person,product_id,`time` ) UNION ( SELECT CONVERT(o.remote_ip,CHAR) AS `person`, oi.product_id, FLOOR(UNIX_TIMESTAMP(DATE_FORMAT(o.created_at,'%Y-%m-%d %H:00:00'))/(3600*1)) AS `time` FROM `sales_flat_order` AS o LEFT OUTER JOIN `sales_flat_order_item` AS oi ON o.entity_id = oi.order_id WHERE o.customer_id IS NULL AND o.status='complete' GROUP BY person,product_id,`time` ) ORDER BY person,product_id ) AS tb
其中3600*1的1可以换成你需要的小时数。