I have a database with articles and stock information (two tables). When entering the article id, I select the article from the article table, do some other stuff and then look in the stock table if the article is available.
This could be an easy peasy SELECT * FROM articles, BUT: my articles table has a field parent_id. If that is set, I should select the parent row. Let me illustrate:
+----+-----------+---------+---------+
| id | parent_id | article | country |
|----|-----------|---------|---------+
| 1 | | abc | uk |
| 2 | | cde | us |
| 3 | | efg | can |
| 4 | 6 | hij | mex |
| 5 | | klm | bra |
| 6 | | nop | us |
| 7 | 8 | qrs | mex |
| 8 | | tuv | uk |
+----+-----------+---------+---------+
If I search for article abc, it should return row 1 with country UK. If I’m searching for hij, the query should return row 6, with country US instead of row 4, with country mex. Is there any way of doing this in MySQL or is it faster/better/the only way to split it up in two queries with PHP?
You can do it with a
LEFTouter join: