skip to Main Content

I have a MySQL table like the following

prod  price1 price2  price3
----  ----   ----    ----
AA    100    200     400
BB    200    300     655

How to write a query in MySQL so that the table appears vertically like this?

prod   price
----   -----
AA      100
AA      200
AA      400
BB      200
BB      300
BB      655       

2

Answers


  1. You could use UNION ALL to do this:

    SELECT prod, price1
    FROM your_table
    UNION ALL 
    SELECT prod, price2
    FROM your_table
    UNION ALL 
    SELECT prod, price3
    FROM your_table
    
    Login or Signup to reply.
  2. SELECT prod, price1 AS price FROM your_table
    UNION ALL
    SELECT prod, price2 AS price FROM your_table
    UNION ALL
    SELECT prod, price3 AS price FROM your_table
    ORDER BY prod;
    

    Replace your table with the actual name of your table. This query will select each product with each of its prices and combine them into a single result set.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search