0

我有两张桌子。

表 db1 和 db2

DB1
+-----------+------------+
|    id     |    nameDb  |
+-----------+------------+
|    1      |    name1   |
+-----------+------------+
|    2      |    name2   |
+-----------+------------+
|    3      |    name3   |
+-----------+------------+

DB2

+------------+------------+-------------+----------------------+
|    id      |   name     |   id_db1    |          date        |
+------------+------------+-------------+----------------------+
|    1       |   test1    |      1      |  2013-05-10 10:00:00 |
+------------+------------+-------------+----------------------+
|    2       |   test2    |      1      |  2013-05-10 11:00:00 |
+------------+------------+-------------+----------------------+
|    3       |   test3    |      1      |  2013-05-10 11:10:00 |
+------------+------------+-------------+----------------------+
|    4       |   test4    |      1      |  2013-05-10 11:40:00 |
+------------+------------+-------------+----------------------+

我的查询是这样的:

SELECT a.nameDb, b.name FROM db1 a 
LEFT JOIN db2 b ON b.id_db1 = a.id 
WHERE DATE_FORMAT(b.name, '%Y-%m-%d') = '2013-05-10'

我需要返回与当天相关的所有内容,不相关的也必须出现......

就像是

+------------+------------+
|    nameDb  |   name     |
+------------+------------+
|    name1   |   test1    |
+------------+------------+
|    name1   |   test2    |
+------------+------------+
|    name1   |   test3    |
+------------+------------+
|    name1   |   test4    |
+------------+------------+
|    name2   |   NULL     |
+------------+------------+
|    name3   |   NULL     |
+------------+------------+

任何想法 ?

4

4 回答 4

2

尝试这个

SELECT a.nameDb, b.name FROM db1 a 
LEFT JOIN db2 b ON b.id_db1 = a.id 
and DATE_FORMAT(b.date, '%Y-%m-%d') = '2013-05-10'

如果在 where 子句中使用左外连接表中的列,它的行为类似于内连接

于 2013-05-02T18:19:33.457 回答
0

你想要一个outer join. 这里对不同的连接及其输出有很好的描述:“INNER JOIN”和“OUTER JOIN”有什么区别?

于 2013-05-02T18:19:39.713 回答
0

你应该只需要一个RIGHT JOIN或交换桌子,你可以使用LEFT JOIN

SELECT a.nameDb, b.name 
FROM db1 a 
  RIGHT JOIN db2 b ON b.id_db1 = a.id AND DATE_FORMAT(b.name, '%Y-%m-%d') = '2013-05-10' 
于 2013-05-02T18:20:09.560 回答
0

您应该将 WHERE 更改为 AND,以将日期检查作为您的加入条件的一部分:

SELECT a.nameDb, b.name FROM db1 a 
LEFT JOIN db2 b ON b.id_db1 = a.id 
AND DATE_FORMAT(b.name, '%Y-%m-%d') = '2013-05-10'
于 2013-05-02T18:20:45.667 回答