Search code examples
mysqldenormalization

SQL Denormalization, Combining table columns to another table columns


I'm having trouble joining together the tables in my database, I want to display it in a specific order heres the example.

Table: product

product_id product_price product_qty
1          5.25          100

Table: product_detail

product_id product_name product_generic_name
1          Alcohol      Isoprophyl Alcohol

And I want the RESULT of the JOINING to be

product_id product_name product_generic_name product_price product_qty
1          Alcohol      Isoprophyl Alchohol  5.25          100

My failed code was:

SELECT `product_detail`.`product_name`,`product_detail`.`product_name`,`product_detail`.`product_generic_name` 
FROM `product_detail`
UNION
SELECT * FROM `product`

But the result is not what I need, it doesnt add columns only the rows. Please give me advice on how to solve this problem,


Solution

  • SELECT p.product_id,
           product_name ,
           product_detail,
           product_generic_name ,
           product_price, 
           product_qty
    FROM product as p
           inner join product_detail as pd on p.id = pd.id
    

    You may want to read up on a few mysql tutorials on how to join tables as this is probably as simple as it gets MySQL Reference manual

    Based on your comments here is another option to try:

    Select * from
             (SELECT p.product_id,
                     product_name ,
                     product_detail,
                     product_generic_name ,
                     product_price, 
                     product_qty
             FROM product as p) as newTable
    

    Or alternatively you could try temporary tables if you want something else.

    create temporary table new_table
    SELECT p.product_id,
                     product_name ,
                     product_detail,
                     product_generic_name ,
                     product_price, 
                     product_qty
             FROM product as p
    

    Then in the same script or however your calling it you could try:

    select * from new_table