SQL查询显示零而不是未显示的记录

时间:2013-12-17 23:58:30

标签: mysql sql

我有这两个表:

接收

id  reception_date      tin_lot company_id  client_id   quantity    weight
1   2013-12-03 00:00:00 1       1           1           10          1980.00
2   2013-12-03 00:00:00 2       1           1           1           150.00
3   2013-12-13 00:00:00 3       1           2           10          4500.00
4   2013-12-13 00:00:00 4       2           5           5           2300.00

付款

id  payment_date        amount  reception_id
1   2013-12-03 00:00:00 500.0   1
2   2013-12-03 00:00:00 1200.0  3

我想获得的结果如下:

预期结果

id  reception_date      tin_lot client_id   weight      payment_made
1   2013-12-03 00:00:00 1       1           1980.00     500.0
2   2013-12-03 00:00:00 2       1           150.00      0.0
3   2013-12-13 00:00:00 3       2           4500.00     1200.0
4   2013-12-13 00:00:00 4       5           2300.00     0.0

我正在尝试此查询:

select rec.id
rec.reception_date,
rec.tin_lot,
rec.client_id,
rec.weight,
pay.payment_made
from liquidation.reception rec, liquidation.payment pay
where pay.recepcion_id=rec.id

但它没有列出没有付款的招待会。

请帮帮我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您需要左加入付款表:

from liquidation.reception rec
left join  liquidation.payment pay on ( pay.recepcion_id=rec.id)

答案 1 :(得分:0)

这是因为您需要学习使用left outer join和正确的连接语法。只是不要在from子句中使用逗号。

以下是您想要的查询:

select rec.id, rec.reception_date, rec.tin_lot, rec.client_id, rec.weight,
       coalesce(pay.payment_made, 0) as payment_made
from liquidation.reception rec left outer join
     liquidation.payment pay
     on pay.recepcion_id = rec.id;