3

我有以下两个需要加入的 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 |
+---------------------+-------------+-------------+

再次感谢!

4

1 回答 1

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

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

于 2013-02-21T22:34:31.610 回答