I have a table looking like this
Table: Stores
| Group | ID | Name | Link |
| 1 | 1 | Store A | |
| 1 | 2 | Store B | 3 |
| 1 | 3 | Store C | |
| 2 | 4 | Store D | |
So, what I want to do is that I want to do a query which is showing as a result the ID and Name of the queried row plus, in case there is a ID mentioned in column "Link", I want to see a new column with the name of the ID where the link refers to.
By this the output of queriying ID 2 should look like:
| ID | Name | Link |
| 2 | Store B | Store C |
I tried it with the following query, but the name of the link is always returned as NULL.
SELECT `ID`, `Name`,(SELECT `Name` FROM `Stores` WHERE Stores.ID = Stores.Link ) AS Link FROM `Stores` WHERE (`ID` LIKE '2');
Is it possible to query a table in this way?
3
Answers
You can left join the same table again with a different alias name
If you use the MySQL default (inner) join, you will get the result, you want.
You need to use an alias in the sub query otherwise mysql doesn’t know you want to test against stores in the main query eg
a self join (as in other answers) will produce the same result
nb group is a reserved word in mysql and not a good name for a column.