mysql:在表上没有记录匹配的连接

时间:2013-11-11 18:12:18

标签: mysql

如果我有2个或多个表,1个表或某些表没有记录,

CREATE TABLE t1
(`id1` int, `date1` datetime, `val1` int)
;
INSERT INTO t1
(`id1`, `date1`,`val1`)
VALUES  
(1, '2013-11-10 14:57:09',10),
(2, '2013-11-10 16:59:37',15),
(4, '2013-11-11 15:12:44',11)
;

CREATE TABLE t2
(`id2` int, `date2` datetime, `val2` int)
;
INSERT INTO t2
(`id2`, `date2`,`val2`)
VALUES  
(1, '2013-11-10 14:57:09',22),
(2, '2013-11-10 16:59:37',4),
(4, '2013-11-12 12:12:44',7)
;

我用这个:

SELECT * 
FROM t1,t2
WHERE 
  (t1.date1 >= '2013-11-11 13:00:00'  AND t1.date1 < '2013-11-11 15:00:00')  and 
  (t2.date2 >= '2013-11-11 00:00:00'  AND t2.date2 < '2013-11-11 23:59:59') 
LIMIT 1

和输出

MySQL returned an empty result set (i.e. zero rows).

因为表t2上没有记录匹配

如果我想要这样的输出

+------+---------------------+------+------+
| id1  | date1               | val1 | val2 |
+------+---------------------+------+------+
|    1 | 2013-11-10 14:57:09 |   10 |    0 |
+------+---------------------+------+------+

这可能吗?

1 个答案:

答案 0 :(得分:3)

使用LEFT JOIN。要连接的表上的任何条件都必须在ON子句中,因为将它们放在WHERE子句中将过滤掉空匹配。

SELECT *
FROM t1
LEFT JOIN t2 ON t2.date2 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'
WHERE t1.date1 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'

以下是如何使用4个表格。

SELECT *
FROM t1
LEFT JOIN t2 ON t2.date2 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'
LEFT JOIN t3 ON t3.date3 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'
LEFT JOIN t4 ON t3.date4 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'
WHERE t1.date1 BETWEEN '2013-11-11 00:00:00'  AND '2013-11-11 23:59:59'