如何从mysql表中获取所有潜在订单

时间:2015-02-07 23:58:57

标签: mysql

我有一个mysql查询,并且无法弄清楚如何从给定的product_id中提取某个country_id的所有潜在客户。我想要一个每个客户只有一条记录的结果 我的表格为orderscustomers

---customers--
customer_id
country_id
name
---orders---
order_id
product_id
customer_id

我目前的查询提供了太多结果。即来自其他product_id的非= 1的记录。这是我的查询:

SELECT o.order_id
     , c.name
     , c.customer_id
     , c.country_id
     , o.product_id 
  FROM customers c 
  LEFT 
  JOIN orders o 
    ON o.customer_id = c.customer_id 
 WHERE o.product_id = 1 
    OR c.country_id = 1

某些示例结果可能如下所示:

order_id    name        customer_id country_id product_id
1           Joe Smith   1           1          1
2           Joe Smith   1           1          2
3           John Doe    2           1          1
4           Kirk Smith  3           1          1
NULL        Ron Rhoden  6           1          1
NULL        Sam Smith   7           1          1

出于我的目的,您可以假设给定的客户只会订购一次给定的产品。请注意我如何使用product_id=2获得Joe Smith的结果。我不希望这个结果出现在我的列表中。 Ron Rhoden和Sam Smith的结果对我来说是可取的。如何过滤product_id<>1条记录但仍包含所有country_id=1条记录? 感谢。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望来自国家&#34; 1&#34;已订购产品&#34; 1&#34;。我建议使用exists

select c.*
from customers c
where c.country_id = 1 and
      exists (select 1
              from orders o
              where o.customer_id = c.customer_id and
                    o.product_id = 1
             );

答案 1 :(得分:0)

这是我的尝试:

SELECT o.order_id
     , c.name
     , c.customer_id
     , c.country_id
     , o.product_id 
FROM customers c 
  LEFT 
  JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IN (SELECT order_id FROM orders WHERE product_id = 1)
OR c.country_id IN (SELECT customers.country_id FROM customers WHERE product_id = 1)
);

答案 2 :(得分:0)

好的,我觉得这很有效。有点复杂,但我首先要求订单中的所有product_id = 1记录然后执行UNION查询,然后询问具有country_id = 1的客户中的每个人,但不是之前的product_id = 1结果。

SELECT o.order_id,c.name,c.customer_id,c.country_id,o.product_id
来自客户c LEFT JOIN命令o ON o.customer_id = c.customer_id  WHERE o.product_id = 1 UNION SELECT NULL AS order_id,c.name,c.customer_id,c.country_id,NULL AS product_id
 来自客户c
 WHERE c.country_id = 1 AND c.customer_id NOT IN(SELECT c2.customer_id FROM customers c2 INNER JOIN orders o2 ON c2.customer_id = o2.customer_id WHERE o2.product_id = 1)