指定没有订单的客户

时间:2014-11-02 09:59:57

标签: php mysql

我有一个像这样的客户表

customers_id   |   customers_date_added
-----------------------------
   1           | 2012-10-13 09:31:38
   2           | 2013-12-13 08:31:38
   3           | 2014-09-13 10:31:38
   4           | 2013-08-13 09:31:38
   5           | 2011-07-13 14:31:38

和这样的订单表

   orders_id   |   customers_id
-------------------------------
     1         |      2
     2         |      3
     3         |      5
     4         |      5
     5         |      2

我试图让那些没有订单且在2012年和2013年注册的客户。在这种情况下,我想获得customers_id 1和4。

这不起作用。

SELECT customers_id
FROM customers
WHERE  customers_id NOT IN (
  SELECT DISTINCT customers_id
  FROM   orders
)
AND EXTRACT(YEAR FROM customers_date_added) = '2013'
OR  EXTRACT(YEAR FROM customers_date_added) = '2012'

我的查询有什么问题?

4 个答案:

答案 0 :(得分:1)

为什么不像这样使用LEFT JOIN:

SELECT customers.customers_id
FROM customers
LEFT JOIN order ON customers.customers_id = order.customers_id
WHERE order.customers_id IS NULL
AND customers.customers_date_added BETWEEN '2012-01-01 00:00:00' AND '2013-12-31 23:59:59'

答案 1 :(得分:0)

使用

SELECT customers_id
FROM   customers
WHERE  customers_id NOT IN (
SELECT customers_id
FROM   order
)

答案 2 :(得分:0)

使用此:

SELECT customers_id
FROM customers 
WHERE customers_id NOT IN (SELECT DISTINCT customer_id FROM orders)
AND   date_added BETWEEN '2012-01-01 00:00:00' AND '2013-12-31 23:59:59'

答案 3 :(得分:0)

实际上你的陈述是有效的,请看小提琴:FIDDLE

您也可以使用相同的结果执行此操作

SELECT customers_id
FROM   customers
WHERE  customers_id NOT IN (
          SELECT DISTINCT customers_id
          FROM   orders
       )
AND customers_date_added LIKE '2013%'
OR  customers_date_added LIKE '2012%'

OR

SELECT customers_id
FROM   customers
WHERE  customers_id NOT IN (
          SELECT DISTINCT customers_id
          FROM   orders
       )
AND EXTRACT(YEAR FROM customers_date_added) IN ('2013', '2012')