Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql self join

Say I have a table like so

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

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

I would like to somehow self join on this table to grab specific cmds and their corresponding values for a particular device.

I do not want just SELECT cmd,value FROM table WHERE device='00:11:22:33:44:55';

Say the values I want correspond to the getname and getlocation commands. I would like to have output something like

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

My sql fu is pretty pants. I've been trying different combinations like SELECT a.value,b.value FROM table AS a INNER JOIN table AS b ON a.device=b.device but I am getting nowhere.

Thanks for any help.

like image 344
tbh1 Avatar asked Apr 13 '11 11:04

tbh1


People also ask

What is self join in PostgreSQL?

A PostgreSQL self-join is a regular join that joins a table to itself using the INNER JOIN or LEFT JOIN . Self-joins are very useful to query hierarchical data or to compare rows within the same table.

What is difference between natural join and self join?

Natural Join joins two tables based on same attribute name and datatypes. Inner Join joins two table on the basis of the column which is explicitly specified in the ON clause.

What is difference between self join and inner join?

An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that satisfy the join condition. A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition.

What is the point of a self join?

A self join allows you to join a table to itself. It helps query hierarchical data or compare rows within the same table. A self join uses the inner join or left join clause.


1 Answers

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';
like image 69
Michael Krelin - hacker Avatar answered Nov 17 '22 18:11

Michael Krelin - hacker