SQL返回默认值,用于不存在属性的连接

时间:2012-04-02 08:13:21

标签: mysql sql

我的sql语句有问题。 我的数据库是MySQL 5.1。

我有两张桌子:

day_table 
date(pk)    note    ...
------- -----   ---
2012-03-29  foo ...
2012-03-30  bar ...
2012-03-31  foobar  ...

other_table
id  fk_date     key     value
--  -------     ---     -----
1   2012-03-29  foo     5
2   2012-03-30  bar     9
3   2012-03-30  foo     4
4   2012-03-31  bar     6
5   2012-03-31  foo     1

所以我需要这样的查询:

SELECT o.value, d.date FROM other_table o join day_table d on (...) where key = "bar" group by d.date;

我需要这样的结果:

result_table
date(pk)    value 
------- -----
2012-03-29  0 (or null) <---- THIS IS IMPORTANT!!!
2012-03-30  9       
2012-03-31  6

我知道问题是加入,但我需要在day_table中获取每个日期。

这可以用(My)SQL吗?

最好的问候

2 个答案:

答案 0 :(得分:3)

您的意思是要包含other_table未加入day_table的行吗?使用LEFT JOIN代替常规JOIN

答案 1 :(得分:3)

使用左连接而不是内连接:

SELECT o.value, d.date FROM day_table o left join other_table d on o.date=d.date and key = "bar" group by d.date;