简体   繁体   中英

SQL join one to many - multiple tables

I have a MySQL database with a table 'items'.

Each item can have multiple prices in the 'prices' table and multiple images in the 'images' table. They both have a one to many relationship to items.

I'd love to have a query that gets me all the data at once, but in with the query I came up with, I get a lot of duplicate records. If an item has 3 prices and 3 images, I get 9 rows for that item (instead of the desired 6):

My query:

SELECT * FROM items 
LEFT JOIN prices 
    ON items.item_id = prices.item_id 
LEFT JOIN images 
    ON items.item_id = images.item_id 
ORDER BY items.item_id

Eg I'd love to have:

itemid
  1    item1          price1              NULL
  1    item1          price2              NULL
  1    item1          price3              NULL
  1    item1           NULL              image1
  1    item1           NULL              image2
  1    item1           NULL              image3
  2    item2 ....

Your best bet here is a UNION query:

    SELECT items.item_id, items.item_name, prices.price, CAST(NULL AS VARCHAR(100)) as image
    FROM items 
    LEFT JOIN prices 
        ON items.item_id = prices.item_id 

    UNION ALL

    SELECT items.item_id, items.item_name, NULL, images.image
    FROM items 
    LEFT JOIN images 
        ON items.item_id = images.item_id 

This will stack each query on top of one another, which is why the CAST() is necessary in the first query as a place holder for the image data that will eventually be stacked in that same column. You may have to change that VARCHAR(100) to match whatever data type is in the images column you are pulling. Furthermore, you will probably have to change the field names since I can't see your schema.

Try with only join not left join , like this:

SELECT * FROM items 
JOIN prices 
    ON items.item_id = prices.item_id 
JOIN images 
    ON items.item_id = images.item_id 
ORDER BY items.item_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM