1

我不确定这个问题的标题是什么。

更新以显示更具体的问题。

我有 2 张桌子。

表_a

+------------+--------+---------+
| date       | used   | solar   |
+------------+--------+---------+
| 2012-03-16 | 20.317 |  -4.167 |
| 2012-03-17 | 17.308 | -38.593 |
| 2012-03-18 |  9.529 | -42.414 |
| 2012-03-19 | 13.266 | -26.372 |
| 2012-03-20 |  7.077 | -41.742 |
| 2012-03-21 |  7.625 | -43.348 |
| 2012-03-22 | 10.943 | -42.025 |
| 2012-03-23 | 11.362 | -38.532 |
| 2012-03-24 | 11.492 |  -9.434 |
| 2012-03-25 | 16.133 |  -8.280 |
| 2012-03-26 | 17.054 | -31.340 |
| 2012-03-27 |  9.356 | -49.759 |
| 2012-03-28 | 11.984 | -16.299 |
| 2012-03-29 | 20.175 |  -6.412 |
| 2012-03-30 | 16.024 | -47.509 |
| 2012-03-31 | 10.605 | -16.102 |
+------------+--------+---------+

表_b

+------------+--------+
| date       | hdd    |
+------------+--------+
| 2012-03-01 | 32.884 |
| 2012-03-02 | 31.402 |
| 2012-03-03 | 22.487 |
| 2012-03-04 | 31.087 |
| 2012-03-05 | 41.679 |
| 2012-03-06 | 39.892 |
| 2012-03-07 | 17.626 |
| 2012-03-08 |  8.433 |
| 2012-03-09 | 29.580 |
| 2012-03-10 | 35.238 |
| 2012-03-11 | 22.453 |
| 2012-03-12 | 11.724 |
| 2012-03-13 |  6.486 |
| 2012-03-14 | 16.140 |
| 2012-03-15 | 21.425 |
| 2012-03-16 | 20.486 |
| 2012-03-17 | 13.744 |
| 2012-03-18 |  8.207 |
| 2012-03-19 |  3.878 |
| 2012-03-20 |  2.679 |
| 2012-03-21 |  2.701 |
| 2012-03-22 |  2.830 |
| 2012-03-23 |  4.219 |
| 2012-03-24 | 15.008 |
| 2012-03-25 | 19.155 |
| 2012-03-26 | 27.850 |
| 2012-03-27 | 32.985 |
| 2012-03-28 | 20.470 |
| 2012-03-29 | 26.230 |
| 2012-03-30 | 26.119 |
| 2012-03-31 | 24.353 |
+------------+--------+

table_a有 16 条记录。table_b有 31 条记录。

如果我用...

SELECT a.date, a.used, b.hdd
FROM table_a a RIGHT JOIN table_b b ON a.date=b.date
WHERE MONTH(a.date) = 3;

我只有 16 行,大概是因为 table_a 只有 16 行。但实际上它必须是 where 子句。我如何将两者结合使用?

如何获取所有 31 行(假设其他 16 行的每个表的日期匹配)。我尝试了左连接,但没有奏效。

SELECT a.date, a.used, b.hdd FROM table_a a
LEFT JOIN table_b b ON a.date=b.date;
4

2 回答 2

4

改为使用RIGHT JOIN,因为您想显示所有 10 条记录table_b

SELECT a.date, a.column1, b.column1 
FROM table_a a RIGHT JOIN table_b b ON a.date=b.date;

或交换表名,以便您仍然可以使用LEFT JOIN

SELECT b.date, b.column1, a.column1 
FROM table_b a LEFT JOIN table_a b ON a.date=b.date;

边注

运行此查询时仅获得 5 条记录的原因,

SELECT a.date, a.column1, b.column1 
FROM table_a a, table_b b 
WHERE a.date=b.date;

是因为它的表现像INNER JOIN

SELECT a.date, a.column1, b.column1 
FROM table_a a INNER JOIN table_b b ON a.date=b.date

INNER JOIN选择在正在连接的另一个表上至少有一个匹配的行。要全面了解联接,请参阅下面的文章。

于 2012-12-06T02:25:32.067 回答
0

尝试这个:

SELECT a.date, a.used, b.hdd FROM table_b b
LEFT JOIN table_a a ON b.date=a.date AND MONTH(a.date) = 3;

或者

SELECT a.date, a.used, b.hdd
FROM table_a a RIGHT JOIN table_b b ON a.date=b.date
WHERE MONTH(b.date) = 3;
于 2012-12-06T11:47:26.820 回答