2

我有两张桌子:一张是 Tour,另一张是 ReservedTour。表格的列是:

Tour       | ReservedTour
===========|=============
id         | id
city       | Tid
capacity   | number
timeout    | .
.          | .
.          | .
.          |
========== |======

我写了一条SQL语句,例如

select *, (select sum(rt.`number`) from ReservedTour as rt where rt.`Tid`=t.id GROUP BY rt.`Tid`) as total
  from Tour as t 
 where City = 'alahom' and '1400-12-13' <= t.`timeout` and 4 < t.`Capacity`- total;

但这有一个错误——总数不正确。

我该如何纠正?

4

2 回答 2

1

试试这个:

select t.*, sum(rt.`number`) as total 
from Tour as t
join  ReservedTour as rt on rt.`Tid`=t.id
where City = 'alahom' and  t.`timeout`=> '1400-12-13' and t.`Capacity`-total > 4
GROUP BY t.id
于 2013-03-09T18:22:25.920 回答
1

我想你可能正在寻找这样的东西:

SELECT T.*, RT.total
FROM Tour T
  JOIN (select Tid, sum(number) total
          from ReservedTour 
          GROUP BY TId ) RT ON T.Id = RT.TiD
WHERE City = 'alahom' 
   AND '1400-12-13' <= t.`timeout` 
   AND 4 < t.Capacity-RT.total;

精简的 SQL Fiddle 演示

于 2013-03-09T18:27:26.340 回答