第一个表是service表,第二个表是reservation表。
我的要求是:首先,我需要从服务表中选择service_id,金额,如果所选的service_id在特定日期的预约表中,那么我需要选择total_seats值。如果从服务表中选择的服务is在预约表中的特定日期不存在,那么我需要选择total_seats值为60。
----------------------
| service_id |amount |
----------------------
| 3000 | 500 |
----------------------
| 3001 | 300 |
----------------------
| 3002 | 800 |
----------------------
---------------------------------------
| bus_service_id | DOJ |total_seats
------------------------------------------
| 3002 | 2013-10-11 | 23
------------------------------------------
| 3001 | 2013-10-6 | 26
------------------------------------------
| 3001 | 2013-10-12 | 50
------------------------------------------
| 3000 | 2013-10-6 | 41
------------------------------------------ 请帮帮我怎么做?我需要传递一个输入参数DOJ。
发布于 2013-09-29 14:23:55
这样就可以了:
SELECT IFNULL(total_seats, 60) total_seats
FROM service_table s
LEFT JOIN reservation_table r
ON s.service_id = r.bus_service_id AND DOJ = @DOJDOJ测试必须在ON子句中,这样测试就不会在没有匹配的情况下过滤掉空行。
发布于 2013-09-29 14:04:56
select case when total_seats is null then 60 else total_seats end as total_seats
from service_table
left outer join reservation_table
on service_table.service_id = reservation_table.bus_service_id
where DOJ = @DOJ您需要使用左外部联接,否则将消除service_table中在reservation_table中没有bus_service_id的值。CASE语句有点像switch语句,所以如果reservation_table中没有匹配值,我们将返回60。您还可以在连接条件中包含DOJ = @DOJ,如果您觉得这更清楚的话。当然,我也省略了参数声明;它将根据它是函数的参数还是脚本的一部分而有所不同。
https://stackoverflow.com/questions/19074966
复制相似问题