Skip to content
Advertisement

SQL table join on itself but allow “0” value

Okay so i have a simple table “category” on this table categories and subcategories are saved. categories have “parent_id=0”, and subcategories have a “parent_id” that equals the row_id of the category.

for example

In this example ‘fruit’ and ‘vegetable’ are categories the rest subcategories, i know on this toppic are already a lot of questions which are answered. But my question is:

how can i join “ID” and “parent_id”. currently I am using “xampp” and when i join the values xampp doesn’t allow:

because it is linked with a primary and foreign key to “ID”.

Advertisement

Answer

Use a self join with an appropriate ORDER BY clause:

Note: The above query might have to be adjusted slightly depending on your actual SQL database.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement