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.
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.
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.
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.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With