1

我有两张桌子,比如unitsprice。单位表字段是unit1, unit2Price表字段是id, rateper, price. 现在我想像表一样连接这两个表Pricerateper <=0然后Price table is empty返回 unit1else rateper。我写了如下查询,但没有工作

 select case when rateper <=0  then unit1 else rateper from units,price

我正在使用postgresql9.0 版

单位表

+------+-----+
|Unit1 |Unit2|
--------------
| 2    | 10  |
| 1    | 20  |
+------+------

价格表

+------+-------------+---------+
|id    + rate per    + price   |
--------------------------------
|1     |0            | 100     |
|2     |1            | 200     |
|3     |2            | 300     |
--------------------------------

Result :

2
1
3

如果价格表没有行,则显示结果为

2
1
4

1 回答 1

0

您必须指定要加入这些表的列

select
    case
        when p.rateper <= 0 or p.rateper is null then u.unit1
        else p.rateper
    end
from units as u
    full outer join price as p on p.id = u.???

更新我认为你需要某种完整的外部连接。我仍然不完全理解你到底想要什么,但试试这个查询:

select
    coalesce(u."Unit1", p."id")
from Units as u
    full outer join (select * from price where "rate per" > 0) as p on p."id" = u."Unit1";

sql 小提琴演示

于 2013-08-16T10:46:45.970 回答