我有以下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'之类的内容,但稍后我会在其工作时添加。
答案 0 :(得分: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'
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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的