Mysql如何从选择结果中创建列名

标签 mysql sql

我想根据列中的子环值从不同的数据库中选择结果。 这是我的表学生:

Original_student        Other_student
1010173                   1240240
1010173                   1240249

编号中的第3位数字将用于区分数据库。例如。我希望查询是

select original_student, Other_student, month
from student join database-(substring(other_student,3,1).payment 

我的问题是:如何动态地将子字符串连接到数据库名称或列名称?

谢谢

最佳答案

假设您有一个字段通过唯一 ID (id_student) 来标识每个学生,这是一个廉价的替代方案:

CREATE OR REPLACE VIEW v_student_payment AS
SELECT 0 AS db, payment, id_student FROM database-0
UNION 
SELECT 1 AS db, payment, id_student FROM database-1
UNION 
SELECT 2 AS db, payment, id_student FROM database-2
UNION 
SELECT 3 AS db, payment, id_student FROM database-3
/* here you have to add all databases you're using. There's a little maintenance cost, for if one day there's a new database to be created this view would have to be modified */
;

SELECT 
    original_student, 
    Other_student, 
    month, 
    v.payment
FROM 
    student s
        JOIN v_student_payment v ON v.id_student = s.id_student AND v.db = SUBSTRING(other_student,3,1) 

关于Mysql如何从选择结果中创建列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827746/

相关文章:

使用 Group By 但需要列 Total 的 SQL 语句

mysql - 如何在 REPLACE() 函数中使用数组?

sql - 使用 ADODB Recordset 更新记录

mysql - 如何在一行中分组和计数?

mysql - 使用 RAND() 从表中随机选择无法正常工作

php - 正在尝试检索个人资料图片

MySQL集群跨多个Slave的负载均衡

mysql - 选择我的问题的陈述

mysql - 简单的 SQL 查询工作台

java.sql.SQLException : Invalid Oracle URL specified Error