我有两张桌子。
表db1 AND 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 |
+------------+------------+
任何想法?
答案 0 :(得分: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子句中使用左外连接表中的列,则其行为类似于内连接
答案 1 :(得分:0)
你想要一个outer join
。这里有不同连接及其输出的良好描述:What is the difference between "INNER JOIN" and "OUTER JOIN"?
答案 2 :(得分: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'
答案 3 :(得分: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'