我想找到所有尚未在2015年订购的经销商。我知道这个查询不起作用,但我认为理解我想做什么可能会有所帮助。在这个例子中,我想得到的只是" Bob"结果是。他是这个例子中唯一一个在2015年没有订单的经销商。
SELECT d.`name`
FROM z_dealer d
LEFT JOIN z_order o ON (d.promo_code = o.promo_code)
WHERE o.promo_code IS NULL
AND o.date_ordered > '2015-01-01 00:00:00'
这是表格数据......
mysql> Select * from z_order;
+----+-------+------------+---------------------+
| id | total | promo_code | date_ordered |
+----+-------+------------+---------------------+
| 1 | 10 | holiday | 2014-06-22 09:06:50 |
| 2 | 20 | special | 2015-06-22 09:07:04 |
| 3 | 15 | holiday | 2015-03-01 09:07:23 |
| 4 | 45 | special | 2014-09-03 09:07:33 |
| 5 | 16 | laborday | 2014-06-22 09:09:01 |
+----+-------+------------+---------------------+
mysql> select * from z_dealer;
+----+------+------------+
| id | name | promo_code |
+----+------+------------+
| 1 | John | holiday |
| 2 | Suzy | special |
| 3 | Bob | laborday |
+----+------+------------+
答案 0 :(得分:1)
select d.`name`
from z_dealer d
where
(select count(*)
from z_order o
WHERE o.promo_code = d.promo_code
AND o.date_ordered > '2015-01-01') = 0
答案 1 :(得分:0)
您需要告诉查询您要比较时间戳而不是字符串,并且需要在JOIN的ON子句中包含所有JOIN条件,而不是在WHERE子句中。将查询更改为
SELECT d.`name`
FROM Table2 d
LEFT JOIN Table1 o ON (d.promo_code = o.promo_code AND
o.date_ordered > TIMESTAMP '2015-01-01 00:00:00')
WHERE o.promo_code IS NULL
祝你好运。
答案 2 :(得分:0)
SELECT d.`name`
FROM z_dealer d
LEFT JOIN z_order o ON (d.promo_code = o.promo_code)
WHERE o.promo_code IS NULL
AND o.date_ordered > 2015-01-01 00:00:00
'之间的日期值'被读取为字符串值而不是DateTime。所以上面的代码工作。如果你想要你的结果" Bob"从查询中删除Where子句,因为它被视为可能会改变结果的谓词。
P.S您不应在日期值中使用连字符作为其表示文化格式。请查看This的良好做法。