【问题标题】:Connect tables with or without records连接有或没有记录的表
【发布时间】:2013-08-16 10:40:17
【问题描述】:

我有两个表,例如 unitsprice。单位表字段为unit1unit2Price 表字段为idrateperprice。现在我想连接这两个表,如Pricerateper <=0Price table is empty 然后返回unit1 否则rateper。我写了如下查询,但没有工作

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

我正在使用postgresql 9.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

【问题讨论】:

  • 黑暗中的野蛮刺伤:你想要LEFT OUTER JOIN。 +1 包括您的版本并做出一些努力;感谢您听取我之前的建议。
  • @CraigRinger 谢谢先生,但我怀疑这些列没有外键。
  • 您可以在任何返回布尔结果的条件下加入。您需要 some 方法将两个表连接在一起,但它不必基于主/外键关系。您还没有显示表格、数据、预期结果,也没有说明您希望如何将两个表格链接在一起,因此很难更具体。

标签: sql postgresql postgresql-9.0


【解决方案1】:

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

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 fiddle demo

【讨论】:

  • 没关系。您将如何确定价格表是否以单位为单位的行为空?
  • 请看我的要求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多