简体   繁体   中英

Find rows with MySQL where column has values 'n' AND others values

Consider the tables order , order_line and product .

order_line has columns order_id and product_id .

I want to find the orders that have order_line with product_category 1 AND other product_categories . Example of the order_line results:

 id | order_id | product_category
----+----------+-------------------
 6  |     5    |    1
 7  |     5    |    2

Category 1 MUST exist, as well as other categories.

I tried the following, but it does not help, it's probably a fault in my logic:

SELECT *
FROM order_line
WHERE
 product_category = 1 AND
 order_id IN (
   SELECT order_id
   FROM order_line
   WHERE
    product_category != 1
 )

If you want the other categories as well as the "1", use two exists :

SELECT ol.*
FROM order_line ol
WHERE EXISTS (select 1 from order_line ol2 where ol2.order_id = ol.order_id and product_category = 1) AND
      EXISTS (select 1 from order_line ol2 where ol2.order_id = ol.order_id and product_category <> 1) ;

This is almost a direct translation of your problem statement.

Note: If you just want the orders that have this condition, I would approach that using a group by :

select ol.order_id, group_concat(distinct product_category) as categories
from orderline ol
group by ol.order_id
having sum(product_category = 1) > 0 and
       sum(product_category <> 1) > 0;

But the first version gives all the order detail.

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