【问题标题】:PostgreSQL: left outer join syntaxPostgreSQL:左外连接语法
【发布时间】:2011-06-02 13:43:09
【问题描述】:

我正在使用 PostgreSQL 8.4.6 和 CentOS 5.5 并且有一个用户表:

# select * from pref_users where id='DE2';
 id  | first_name | last_name | female |      avatar      |        city         | lat | lng |           login            | last_ip | medals |           logout
-----+------------+-----------+--------+------------------+---------------------+-----+-----+----------------------------+---------+--------+----------------------------
 DE2 | Alex       |           | f      | 2_1280837766.jpg | г. Бохум в Германии |     |     | 2011-01-02 19:26:37.790909 |         |        | 2011-01-02 19:29:30.197062
(1 row)

另一个表格列出了他们每周在游戏中赢得的“虚拟货币”:

# select * from pref_money where id='DE2';
 id  | money |   yw
-----+-------+---------
 DE2 |    66 | 2010-48
(1 row)

然后我尝试为用户显示这两个信息,但我只对用户本周的钱感兴趣:

# select u.id,
    u.first_name,
    u.city,
    u.avatar,
    m.money,
    u.login > u.logout as online
from pref_users u, pref_money m where
    m.yw=to_char(current_timestamp, 'YYYY-IW') and
    u.id=m.id and
    u.id='DE2'
order by m.money desc;
 id | first_name | city | avatar | money | online
----+------------+------+--------+-------+--------
(0 rows)

在这种情况下,我没有任何行,因为用户“DE2”本周还没有赚取任何“虚拟货币”。

我想更改我的查询,以便它始终返回现有用户的数据,如果他们本周没有玩 - 那么查询应该返回 0。

所以我想我需要一个outer left join,我正在尝试:

 select u.id,
    u.first_name,
    u.city,
    u.avatar,
    m.money,
    u.login > u.logout as online
from pref_users u left outer join pref_money m on (
    m.yw=to_char(current_timestamp, 'YYYY-IW') and
    u.id=m.id and
    u.id='DE2')
order by m.money desc;

但是这些返回给我很多不同用户的行,而不是只有一个 id='DE2' 的行。

请问我做错了什么?

【问题讨论】:

    标签: postgresql left-join outer-join


    【解决方案1】:
    select u.id,
           u.first_name,
           u.city,
           u.avatar,
           coalesce(m.money,0),
           u.login > u.logout as online
      from pref_users u left outer join pref_money m on u.id=m.id
           and m.yw=to_char(current_timestamp, 'YYYY-IW') 
     where u.id='DE2'
     order by m.money desc;
    

    【讨论】:

    • 编辑:将 m.yw 添加回 on-clause
    【解决方案2】:

    您希望将过滤条件u.id='DE2' 放在 WHERE 子句中,而将其他所有内容放在 ON 子句中。对于每个 ON 不匹配的用户,它仍然会输出带有来自 u 的数据和 m 的空值的行。

    【讨论】:

      【解决方案3】:

      尝试移动

      u.id='DE2'
      

      进入 WHERE 子句,如下所示:

      select u.id,
          u.first_name,
          u.city,
          u.avatar,
          m.money,
          u.login > u.logout as online
      from pref_users u left outer join pref_money m on u.id=m.id
      where m.yw=to_char(current_timestamp, 'YYYY-IW') and
          u.id='DE2'
      order by m.money desc;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 2011-10-01
        • 2012-04-29
        • 2016-03-14
        • 2012-02-04
        • 2011-09-14
        • 1970-01-01
        相关资源
        最近更新 更多