2011-04-13 55 views
6

说我有一个像表,以便PostgreSQL的自联接

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

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

我想以某种方式自我加入此表上抢具体CMDS及其对应的值特定设备。

我不想只是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福是漂亮的裤子。我一直在尝试像SELECT a.value,b.value FROM table AS a INNER JOIN table AS b ON a.device=b.device这样的不同组合,但我无处可去。

感谢您的任何帮助。

回答

6
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'; 
+0

谢谢你。我想如果我想要四个值而不是两个,我需要三个JOIN的? – tbh1 2011-04-13 12:39:48

+0

是的,但是如果这很重要,也许你想重新考虑你的数据库结构;-) – 2011-04-13 12:54:29

+0

另一种可能性是使用group by并在选择列表中对它们进行排序。 – 2011-04-13 12:54:59