-1

如果我有 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 |
+------+---------------------+------+------+

这可能吗?

4

1 回答 1

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'
于 2013-11-11T18:27:35.140 回答