我不确定这个问题的标题是什么。
更新以显示更具体的问题。
我有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;
答案 0 :(得分:4)
请使用RIGHT JOIN
,因为您要显示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
选择要加入的另一个表上至少有一个匹配的行。要完全了解联接,请参阅以下文章。
答案 1 :(得分: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;