简体   繁体   中英

Getting all different values but not duplicates from multiple records

I have the following 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()

I also have these tables:

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

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

I want to get all orders where deadline hasn't passed and group them by product_manufacturer, but if an order has three order lines, that all have the product_manufacturer id, then it should only return the id ones. If it has the two order lines with different product_manufacturer id, then it should return the id twice and so on.

I'm using PHP and I would like to end up with an array like this:

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

SONY
Order 1
Order 2
Order 16
Order 99

PROSONIC
Order 3
Order 88
Order 98

Later it should be possible to search, so I will have to make something like WHERE ol.product_name LIKE '%$query', but I will add that later on, when it works.

As far as I can see you cannot get that form of output from a single SQL command. I suggest you to get SELECT DISTINCT product_manufacturer FROM order_lines and then search from all orders where deadline hasn't passed for each product_manufacturer. For ex:

 SELECT o.order_id  FROM orders o, order_lines ol  
 WHERE o.deadline_time > UNIX_TIMESTAMP() 
 AND ol.product_manufacturer='$pro_man'
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

This will return

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

This will return

Order_id   manufacturerid
    1          999
    2          sony

@UlrikMcArdle

why isn't the first query with ORDER BY what you are looking for?

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
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 

you can use some sort of UDF to concat all the order_id for the manufacture.

Click here for similar UDF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM