Skip to content
Advertisement

MySQL query to Retrieve Main record from main table and Sub records from another table in a single SQL statement

I have following Two tables

Table Name: category

categoryid         Categoryname
1                  Mobiles
2                  Laptops

Table Name: product

productid          categoryid         productname
1                  1                  Nokia
2                  2                  Dell
3                  1                  Mi
4                  1                  Samsung
5                  2                  Lenovo

Now I am looking for single SQL statement which should retrieve everything in a single sql statement.

Expected output given below:

recordtype        categoryid     productid           category       productname
Category          1              0                   Mobiles
Product           1              1                                  Nokia  
Product           1              3                                  Mi
Product           1              4                                  Samsung
Category          2              0                   Laptops
Product           2              2                                  Dell
Product           2              5                                  Lenovo    

Advertisement

Answer

You can use union all:

select 'category' as recordtype, categoryid, 0 as productid, categoryname as category, null as product
from category
union all
select 'product', categoryid, productid, null, productname
from product;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement