Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all the sub_category records with its main_category_name and parent_id in a single query in MySQL?

Tags:

php

mysql

My category table is looking like the following:

------------------------------------
id  |   name         | parent_id   |
------------------------------------
1   |  Vehicles      |   0         |
2   |  Car Insurance |   1         |
3   |  Van Insurance |   1         |
4   |  PhoneRecharge |   0         |
5   |  prepaid       |   4         |
6   |  postpaid      |   4         |

The output should look like the following:

---------------------------------------------------------
id  | parent_id | main_category_name | sub_category_name|
---------------------------------------------------------
2   |  1        |   Vehicles         | Car Insurance    |
3   |  1        |   Vehicles         | Van Insurance    |
5   |  4        |   PhoneRecharge    | prepaid          |
6   |  4        |   PhoneRecharge    | postpaid         |

To get the above record, I need to minimize my database interaction. So I need to achieve this above data in a single query.

like image 921
Chandrakar Ramkishan Avatar asked Nov 05 '16 04:11

Chandrakar Ramkishan


People also ask

How do I select all values in a column in MySQL?

We use the SELECT * FROM table_name command to select all the columns of a given table. In the following example we are selecting all the columns of the employee table. mysql> SELECT * FROM employee; And we get the following output.

What is the correct command in selecting all data in MySQL?

This form of SELECT uses * , which is shorthand for “select all columns.” This is useful if you want to review your entire table, for example, after you've just loaded it with your initial data set.

How display all records in MySQL table?

The first command you will need to use is the SELECT FROM MySQL statement that has the following syntax: SELECT * FROM table_name; This is a basic MySQL query which will tell the script to select all the records from the table_name table.

How do I select a specific row in a table in MySQL?

MySQL SELECT specific rows When a user wants to retrieve some individual rows from a table, a WHERE clause has to be added with the SELECT statement immediately followed by a condition.


1 Answers

Here you go: http://sqlfiddle.com/#!9/1b1a7a/14

SQL: SELECT * FROM category t1 INNER JOIN (SELECT * FROM category WHERE parent_id != 0) t2 ON t1.id = t2.parent_id

like image 184
junkfoodjunkie Avatar answered Sep 19 '22 16:09

junkfoodjunkie