【问题标题】:postgresql self joinpostgresql 自连接
【发布时间】:2011-08-04 15:04:39
【问题描述】:

假设我有一张这样的桌子

  id  |     device     |  cmd  | value | 
------+----------------+-------+---------

id = unique row ID
device = device identifier (mac address)
cmd = some arbitrary command
value = value of corresponding command

我想以某种方式在此表上自行加入,以获取特定设备的特定 cmd 及其对应值。

我不想要SELECT cmd,value FROM table WHERE device='00:11:22:33:44:55';

说出我想要对应getnamegetlocation 命令的值。我想输出类似的东西

        mac         |    name   | location
--------------------+-----------+------------
 00:11:22:33:44:55  | some name | somewhere

我的 sql fu 是漂亮的裤子。我一直在尝试不同的组合,例如 SELECT a.value,b.value FROM table AS a INNER JOIN table AS b ON a.device=b.device,但我一无所获。

感谢您的帮助。

【问题讨论】:

    标签: postgresql join


    【解决方案1】:
    SELECT a.value AS thisval ,b.value AS thatval
    FROM table AS a JOIN table AS b USING (device)
    WHERE a.command='this' AND b.command='that';
    

    【讨论】:

    • 谢谢。我想如果我想要四个值而不是两个,我需要三个 JOIN?
    • 是的,但如果这很重要,您可能需要重新考虑您的数据库结构;-)
    • 另一种可能性是使用 group by 并在选择列表中对它们进行排序。
    • 感谢您的帮助,我会调查这些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    相关资源
    最近更新 更多