首页 新闻 赞助 找找看

多表查询,查询某一天的房间价格,如果当天没有price记录,只返回房间信息,其它为空

0
悬赏园豆:100 [已解决问题] 解决于 2016-04-28 18:09

我有两张表room、room_price;

room             room_price
roomid | roomname     id | roomid |      date      | price
       1  | test1        1 |    1    | 20160304   |20
  2   | test2
 
 
现在想查询某一天的房间价格,如果room_price没有当天记录,只返回房间信息,其它为空.
如上图:roomid为1、2的房间信息都会返回,当天有价格信息就返回价格信息
 
我现在用连接查询发现:如果room_price没有当天记录,就不会返回房间信息。能不能用sql语句直接解决这个问题。
笑天下的主页 笑天下 | 初学一级 | 园豆:85
提问于:2016-04-28 17:25
< >
分享
最佳答案
0

select * from room a

left join price b

on a.roomid=b.roomid

where b.date='20160428'

收获园豆:50
skin33 | 初学一级 |园豆:110 | 2016-04-28 17:38

这样不行吧,,这样子应该查不到roomid为2的房间信息了吧

笑天下 | 园豆:85 (初学一级) | 2016-04-28 17:44

@笑天下: 可以的 因为是左链接 取不到会返回NULL  我确定

skin33 | 园豆:110 (初学一级) | 2016-04-28 17:45

@skin33: 

room             room_price
roomid | roomname     id | roomid |      date      | price
       1  | test1        1 |    1    | 20160304   |20
  2   | test2
 
select * from room a

left join price b

on a.roomid=b.roomid

where b.date='20160304';
 
的确只有一条记录。。where b.date='20160304';会对连接的数据做过滤吧
我还没开通博客不能上传图片
笑天下 | 园豆:85 (初学一级) | 2016-04-28 17:55

@笑天下: 现在想查询某一天的房间价格,如果room_price没有当天记录,只返回房间信息,其它为空.

你提问是这样子的 我想你是不是想说有没有那天的数据都返回

    1  | test1        1 |    1    | 20160304   |20
  2   | test2                    null  null    null   null
这样子嘛?
skin33 | 园豆:110 (初学一级) | 2016-04-28 17:57

@skin33: 是的

笑天下 | 园豆:85 (初学一级) | 2016-04-28 18:02

@笑天下:  where b.date='20160304' or b.date is null 

这样就好啦  

skin33 | 园豆:110 (初学一级) | 2016-04-28 18:03

@skin33: 这样可以

笑天下 | 园豆:85 (初学一级) | 2016-04-28 18:07
其他回答(2)
0

左联接

room

left join price

on ...

where price = ? or price is null

狂乱の貴公子 | 园豆:262 (菜鸟二级) | 2016-04-28 17:33

room

left join price

on ...

where price = ? or price is null

and price.date = "....";

这样还是会把当天没有price记录的信息过滤掉吧。。

我问题没描述好,price表里没有记录不是没有price字段。

支持(0) 反对(0) 笑天下 | 园豆:85 (初学一级) | 2016-04-28 17:41
0
select
    a.*,
    b.price
from
    room a
    left join (select roomid, price from room_price where date='20160304') b on a.roomid=b.roomid

 

收获园豆:50
Rich.T | 园豆:3440 (老鸟四级) | 2016-04-28 17:57

OK,这个可以

支持(0) 反对(0) 笑天下 | 园豆:85 (初学一级) | 2016-04-28 18:07

@笑天下: 那结贴吧

支持(0) 反对(0) Rich.T | 园豆:3440 (老鸟四级) | 2016-04-28 18:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册