gpt4 book ai didi

Mysql 通过连接在多个表中进行选择

转载 作者:行者123 更新时间:2023-11-29 14:55:13 24 4
gpt4 key购买 nike

我的数据库中有许多表来存储不同的产品类型(这些产品具有重叠的列,但也有一些产品特有的列)。产品与制造商(其详细信息存储在自己的表中)和类别相关联。我需要制定一个选择语句,该语句将从多个表中获取所有产品以及制造商详细信息和类别详细信息(以便我可以显示长格式的制造商和类别名称)。下表示例:

product_table1:
product_id,
manufacturer_id,
category_id,
product_name,
...

product_table2:
product_id,
manufacturer_id,
category_id,
product_name,
...

category_table:
category_id,
category_name
...

manufacturer_table:
manufacturer_id,
manufacturer_name
...

我需要获取(包含所有产品表中的行):

manufacturer_id,
category_id,
product_name,
... other product columns common to all product tables
... I can hard code these if necessary, they don't have
... to be worked out
manufacturer_name,
category_name

我愿意考虑架构更改,尽管不能将所有产品存储在单个表中(列太多,而 MySQL 可以处理它,维护和理解它会变得很困难)。

我知道我可以通过多项选择来做到这一点,但我真的不想这样做。此外,也不能选择将公共(public)列提取到它们自己的表中。由此引入了其他级别的复杂性。

最佳答案

这是一种方法,但可能存在效率问题:

SELECT all_products.manufacturer_id, all_products.category_id, all_products.product_name, manufacturer.manufacturer_name, category.category_name
FROM manufacturer
JOIN
(
SELECT manufacturer_id, category_id, product_name
FROM product_table1
UNION ALL
SELECT manufacturer_id, category_id, product_name
FROM product_table2
) AS all_products ON all_products.manufacturer_id = manufacturer.manufacturer_id
JOIN category ON category.category_id = all_products.category_id

关于Mysql 通过连接在多个表中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com