I want to select data from two tables, category
and sub_category
.
But I only get the column names of category
. I want both category
and sub_category
.
Here is the result:
{ category_id: 3, category: 'GARDEN' },
{ category_id: 6, category: 'ART' },
{ category_id: 4, category: 'CONSOLE' },
{ category_id: 2, category: 'ELECTRONICS' },
{ category_id: 4, category: 'ELECTRONICS' },
{ category_id: 2, category: 'CONSOLE' },
{ category_id: 5, category: 'CHAIR' },
{ category_id: 6, category: 'COLORS' },
{ category_id: 5, category: 'GARDEN' },
{ category_id: 1, category: 'CONSOLE' },
{ category_id: 3, category: 'CUT' },
{ category_id: 1, category: 'ELECTRONICS' }
Here is my code:
SELECT
c.id AS category_id,
c.category
FROM
category c
UNION
SELECT
sc.id AS sub_category_id,
sc.sub_category
FROM
sub_category sc
€:
here is my expected result:
{ category_id: 3, category: 'GARDEN' },
{ category_id: 6, category: 'ART' },
{ category_id: 4, category: 'CONSOLE' },
{ category_id: 2, category: 'ELECTRONICS' },
{ category_id: 4, category: 'ELECTRONICS' },
{ category_id: 2, category: 'CONSOLE' },
{ category_id: 5, category: 'CHAIR' },
{ category_id: 6, category: 'COLORS' },
{ sub_category_id: 5, category: 'GARDEN' },
{ sub_category_id: 1, category: 'CONSOLE' },
{ sub_category_id: 3, category: 'CUT' },
{ sub_category_id: 1, category: 'ELECTRONICS' }
2
Answers
The problem is that you are using a UNION operation, which combines the results of two queries vertically, but it discards the column names from the second query and renames the columns based on the first query.
You should use a JOIN operation instead!
If you want to be able to differentiate what table the rows came from in a
UNION
statement, you can e.g. add a separate column to your result set to specify that – something like this:Then the result you get will contain either
Category
orSubcategory
in the newsource_table
column to tell you where the row came from.