简体   繁体   English

SQL连接一对多-多个表

[英]SQL join one to many - multiple tables

I have a MySQL database with a table 'items'. 我有一个带有表“项目”的MySQL数据库。

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): 如果一个项目有3个价格和3张图像,则该项目将获得9行(而不是所需的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: 您最好的选择是UNION查询:

    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. 这将使每个查询彼此堆叠,这就是为什么在第一个查询中必须使用CAST()作为最终将存储在同一列中的图像数据的占位符。 You may have to change that VARCHAR(100) to match whatever data type is in the images column you are pulling. 您可能必须更改VARCHAR(100)才能匹配要提取的图像列中的任何数据类型。 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: 尝试仅join而不是left join ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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