gpt4 book ai didi

mysql - 连接结果作为列名

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

我有这个Mysql场景

table1
--------------
id `7` `8`
--------------
1 10 20
2 20 30

table 2
---------------
id code rel
---------------
3 7 1
4 8 2

我正在使用以下语句来获取值

SELECT t2.id, t2.code, 
CASE t2.code WHEN 7 THEN (SELECT `7` FROM table1 t1 where t1.id = t2.rel)
CASE t2.code WHEN 8 THEN (SELECT `8` FROM table1 t1 where t1.id = t2.rel)
END as val
FROM table2 t2

但它既不美观也不实用,因为我需要对这些值求和、相乘等,并且有很多列。

有没有办法连接这些表并获取 table1.7 的 t2.rel、t2.code 值的值?类似于

SELECT t2.id, t2.code, eval(t1.(t2.code))  as val
FROM table2 t2
JOIN table1 t1 on t2.rel = t1.id

非常感谢!

最佳答案

在您准备查询时,SQL 查询中引用的每一列都必须固定。没有 eval 这样的东西。

但是您可以使用数据值来驱动 CASE 语句:

SELECT t2.id, t2.code,
CASE t2.code WHEN '7' THEN t1.`7` WHEN '8' THEN t1.`8` END AS `val`
FROM table2 t2
JOIN table1 t1 ON t2.rel = t1.id;

但是在准备查询之前,您必须对所有情况进行硬编码。 SQL 无法在执行期间生成表达式,因为它会在连续的数据行上找到新的 code 值。

关于mysql - 连接结果作为列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8422934/

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