mysql根据另一个select选择列的值

时间:2013-12-31 11:54:46

标签: mysql sql

我有两张桌子:

TABLE 1:
|| route_id || years ||
===========================
|| 1        || 10    ||

|| 2        || 15    ||

表2:

|| route_id || years_1 || years_5 || years_10 || years_15 ||

|| 1        || 0.5     || 0.6     || 0.7     || 0.8     ||
|| 2        || 0.3     || 0.35     || 0.4     || 0.45     ||

我想根据表1中的值从表2中选择一个值。 例如:
从表2中选择年份_ +(从表1中选择年份,其中route_id = 1),其中route_id = 1

有可能吗?

额外信用:):

我不想使用案例,因为有很多列......

整个陈述是一种观点。

此声明属于COALESCE,因此如果没有任何具有此值的列,请选择另一列。

感谢您的帮助!!!!

这是我现在的声明:

select 
        `a`.`user_id` AS `userId`,
        `a`.`answer_type` AS `answerType`,
        `a`.`route_number` AS `routeNumer`,
        `a`.`route_amount` AS `routeAmount`,
        `a`.`route_years` AS `routeYears`,
        `a`.`route_intrest` AS `routeIntrest`,
        `a`.`route_linkage` AS `routeLinkage`,
COALESCE('r2.intrest_year_XXXXXX'),r.route_intrest) as routeRate
    from
        (`algoanswer` `a`
        left join `route` `r` ON ((`a`.`route_number` = `r`.`route_id`))
        left join `route_intrest` `r2` ON ((`a`.`route_number` = `r2`.`route_id`)))
    where
        (`a`.`answer_id` = (select 
                max(`algoanswer`.`answer_id`)
            from
                `algoanswer`
            where
                (`a`.`user_id` = `algoanswer`.`user_id`)))

我需要输入正确的年份而不是xxx:COALESCE('r2.intrest_year_XXXXXX'),r.route_intrest)作为routeRate

3 个答案:

答案 0 :(得分:3)

我认为这对你有用

SET @config := (select years from table1 where route_id = 1);
SET @sql := CONCAT('SELECT years_', @config, ' FROM table2 where route_id = 1');

PREPARE stmt FROM @sql;
EXECUTE stmt;

答案 1 :(得分:0)

我不确定你想要什么。我假设你想根据每个route_id对table1中的所有年份求和?

SELECT 
    t2.*, 
    SELECT 
        SUM(years) 
        FROM table1 t1 
        GROUP BY t1.route_id 
        WHERE t1.route_id = t2.route_id
    AS years_
FROM 
    table2 t2
WHERE 
    t2.route_id = 1

答案 2 :(得分:0)

试试这个

declare @sql nvarchar(100),
@columnname nvarchar(50);

set @sql=(select 'years_'+ cast((t1.years) as nvarchar(10)) from table1 t1 where t1.route_id=1);
set @columnname=@sql;
select @columnname from table2 ;