gpt4 book ai didi

mySQL 从表中选择值,其中表名称基于字段值

转载 作者:行者123 更新时间:2023-11-29 10:12:27 25 4
gpt4 key购买 nike

这是我的表格的非常简化的版本。

[stock_adjust]
id
batch_table_name
batch_id
adjustment_reason
qty

[ingredient_batch]
id
batch_name
...lots of other columns

[product_batch]
id
batch_name
...lots of other columns

[packaging_batch
id
batch_name
...lots of other columns

stock_adjustbatch_table_name列中包含正确批处理表的名称,该名称可以是“ingredient_batch”、“product_batch”或“packaging_batch”。我需要从正确的批处理表中获取每个条目的值。其伪代码如下所示:

SELECT sa.id, sa.adjustment_reason, sa.qty, batch.batch_name 
FROM stock_adjust AS sa, [sa.batch_table_name] AS batch
WHERE sa.batch_id=batch.id

我已经尝试尽可能地简化描述和表格,希望我没有简化太多并且上面的内容有意义吗?

我发现了几个与以下类似问题有关的问题,但它们要么在这种情况下无法正常工作,要么我没有正确理解该问题。

最佳答案

虽然我建议更新您的数据库架构,但根据您的情况,这里有一种适合您的方法:

select sa.id, b.batch_name
from stock_adjust sa join (
select id, batch_name, 'ingredient_batch' table_name from ingredient_batch
union all
select id, batch_name, 'product_branch' table_name from product_branch
union all
select id, batch_name, 'packaging_batch' table_name from packaging_batch
) b on sa.batch_table_id = b.id and b.table_name = sa.batch_table_name

关于mySQL 从表中选择值,其中表名称基于字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50742639/

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