Ind F. Ashiku Ind F. Ashiku - 2 months ago 5
MySQL Question

MySQL query to get multiple columns to 3 columns

I have a the following mysql table and records:
http://sqlfiddle.com/#!9/fb7c68/1

I want to make a query that will show the records in 3 columns

product_id, parent_option_id, parent_option_value_id (only if the parent_option_id > 0)
.
.
.
.
product_id, child_option_id, child_option_value_id (only if the child_option_id > 0)
.
.
.
.
product_id, grandchild_option_id, grandchild_option_value_id (only if the grandchild_option_id > 0)

Answer

If I correctly understood, what you want to do, try it with 3 queries combinded by UNION.

SELECT 
  product_id as id,
  parent_option_id as option_id, 
  parent_option_value_id as option_value_id 
FROM option_value
WHERE
  parent_option_id > 0
UNION
SELECT 
  product_id as id,
  child_option_id as option_id, 
  child_option_value_id as option_value_id
FROM option_value
WHERE
  child_option_id > 0
UNION
SELECT 
  product_id as id,
  grandchild_option_id as option_id, 
  grandchild_option_value_id as option_value_id
FROM option_value
WHERE
  grandchild_option_id > 0;
Comments