MySQL左连接和右表中的NULL列

时间:2013-02-21 21:41:49

标签: mysql null left-join

我需要加入以下两个MySQL表:

CREATE TABLE `tbl_L` (
  `datetime` datetime NOT NULL,
  `value` decimal(14,8) DEFAULT NULL,
  `series_id` int(11) NOT NULL,
  PRIMARY KEY (`series_id`,`datetime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `tbl_R` (
  `datetime` datetime NOT NULL,
  `value` decimal(14,8) DEFAULT NULL,
  `series_id` int(11) NOT NULL,
  PRIMARY KEY (`series_id`,`datetime`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

我需要从tbl_L中选择所有日期和值,还要选择tbl_R中与tbl_L中的条目具有相同日期时间的值。一个简单的联接,像这样:

SELECT tbl_L.datetime AS datetime, tbl_L.value AS val_L, tbl_R.value AS val_R 
FROM tbl_L 
    LEFT JOIN tbl_R 
        ON tbl_L.datetime = tbl_R.datetime
WHERE 
   tbl_L.series_id = 1 AND tbl_R.series_id = 2 ORDER BY tbl_L.datetime ASC

无效,因为它只会返回tbl_L和tbl_R中的日期时间(因为WHERE子句中提到了右表)。

将查询修改为如下所示:

SELECT tbl_L.datetime AS datetime, tbl_L.value AS val_L, tbl_R.value AS val_R 
FROM tbl_L 
    LEFT JOIN tbl_R 
        ON tbl_L.datetime = tbl_R.datetime 
           AND tbl_R.series_id = 2 
           AND tbl_L.series_id = 1
ORDER BY tbl_L.datetime ASC;

显着减慢速度(从几毫秒到几秒)。

修改:并且实际上也无法正常工作。我将澄清我需要实现的目标:

假设表格中包含以下数据:

mysql> SELECT * FROM tbl_R;
+---------------------+------------+-----------+
| datetime            | value      | series_id |
+---------------------+------------+-----------+
| 2013-02-20 19:21:00 | 5.87000000 |         2 |
| 2013-02-20 19:22:00 | 5.90000000 |         2 |
| 2013-02-20 19:23:00 | 5.80000000 |         2 |
| 2013-02-20 19:25:00 | 5.65000000 |         2 |
+---------------------+------------+-----------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM tbl_L;
+---------------------+-------------+-----------+
| datetime            | value       | series_id |
+---------------------+-------------+-----------+
| 2013-02-20 19:21:00 | 13.16000000 |         1 |
| 2013-02-20 19:23:00 | 13.22000000 |         1 |
| 2013-02-20 19:24:00 | 13.14000000 |         1 |
| 2013-02-20 19:25:00 | 13.04000000 |         1 |
+---------------------+-------------+-----------+
4 rows in set (0.00 sec)

同样,我需要 tbl_L 中的所有条目与 tbl_R 中与日期时间匹配的条目一起加入,否则为NULL。

我的输出应如下所示:

+---------------------+-------------+-------------+
| datetime            | val_L       | val_R       |
+---------------------+-------------+-------------+
| 2013-02-20 19:21:00 | 13.16000000 | 5.870000000 |
| 2013-02-20 19:23:00 | 13.22000000 | 5.800000000 |
| 2013-02-20 19:24:00 | 13.14000000 | NULL        |
| 2013-02-20 19:25:00 | 13.04000000 | 5.650000000 |
+---------------------+-------------+-------------+

再次感谢!

1 个答案:

答案 0 :(得分:4)

您可以通过将tbl_R的条件仅移动到联接的ON子句中来获取所需的数据,如下所示:

SELECT tbl_L.datetime AS datetime, tbl_L.value AS val_L, tbl_R.value AS val_R 
FROM tbl_L 
LEFT JOIN tbl_R 
    ON tbl_L.datetime = tbl_R.datetime
        AND tbl_R.series_id = 2
WHERE 
tbl_L.series_id = 1 ORDER BY tbl_L.datetime ASC

此外,tbl_L上没有用于查询的索引。在tbl_L.series_id上添加索引将有助于查询的性能。