1

我有以下 SQL:

SELECT o.order_id, ol.product_manufacturer 
FROM orders o 
INNER JOIN order_lines ol 
ON o.order_id = ol.order_id 
WHERE o.deadline_time > UNIX_TIMESTAMP()

我也有这些表:

orders:
order_id, somefield, somefield, somefield...

order_lines:
id, order_id, product_manufacturer, somefield, somefield...

我想获取所有未超过截止日期的订单,并按 product_manufacturer 对它们进行分组,但如果一个订单有三个订单行,它们都具有 product_manufacturer id,那么它应该只返回 id 的。如果它有两个具有不同 product_manufacturer id 的订单行,那么它应该返回 id 两次,依此类推。

我正在使用 PHP,我想最终得到一个这样的数组:

$group[manufacturer_id] = array(order_id, order_id, order_id);

编辑:实际上我希望它返回manufacturer_id = 999,如果订单中有多个制造商ID。对不起这个错误。

EDIT2:我正在列出所有订单,但我必须按制造商列出它们。像这样:

SONY
Order 1
Order 2
Order 16
Order 99

PROSONIC
Order 3
Order 88
Order 98

稍后应该可以搜索,所以我将不得不制作类似 WHERE ol.product_name LIKE '%$query' 之类的东西,但稍后我会在它起作用时添加它。

4

4 回答 4

1

据我所知,您无法从单个 SQL 命令获得这种形式的输出。我建议您获取SELECT DISTINCT product_manufacturer FROM order_lines并搜索每个 product_manufacturer 的截止日期尚未过去的所有订单。例如:

 SELECT o.order_id  FROM orders o, order_lines ol  
 WHERE o.deadline_time > UNIX_TIMESTAMP() 
 AND ol.product_manufacturer='$pro_man'
于 2013-07-10T07:36:37.970 回答
1
SELECT o.order_id,group_concat(distinct(ol.product_manufacturer )) as manufacturer
FROM orders o 
INNER JOIN order_lines ol 
ON o.order_id = ol.order_id 
WHERE o.deadline_time > UNIX_TIMESTAMP()
group by o.order_id

这将返回

Order_id   manufacturer
1          sony, panasonic
2          sony

SELECT o.order_id,
CASE WHEN count(distinct(ol.product_manufacturer )) >1  
                  THEN '999' ELSE product_manufacturer END as manufacturerid  
FROM orders o 
INNER JOIN order_lines ol 
ON o.order_id = ol.order_id 
WHERE o.deadline_time > UNIX_TIMESTAMP()
group by o.order_id

这将返回

Order_id   manufacturerid
    1          999
    2          sony
于 2013-07-10T08:13:44.580 回答
0

@UlrikMcArdle

为什么第一个查询不是ORDER BY您要查找的内容?

SELECT o.order_id, ol.product_manufacturer 
FROM orders o 
INNER JOIN order_lines ol ON o.order_id = ol.order_id 
WHERE o.deadline_time > UNIX_TIMESTAMP()
ORDER ol.product_manufacturer, o.order_id
于 2013-07-10T08:28:47.090 回答
0
SELECT ol.product_manufacturer 
FROM orders o 
INNER JOIN order_lines ol 
ON o.order_id = ol.order_id 
WHERE o.deadline_time > UNIX_TIMESTAMP()
GROUP BY ol.product_manufacturer 

您可以使用某种 UDF 来连接制造商的所有 order_id。

单击此处查看类似的 UDF

于 2015-08-27T03:30:31.663 回答