【问题标题】:Dynamic conversion of string into column name. MySQL将字符串动态转换为列名。 MySQL
【发布时间】:2012-11-08 05:00:39
【问题描述】:

我有两张桌子:itemsorders

items
--------------
id (int) | type_1 (int) | type_2  (int)|

orders
--------------
id (int) | transaction_type enum ('type_1', 'type_2')

基本上,我想做以下事情:

select (select transaction_type from orders where id=1) from items;

所以,问题是select transaction_type from orders where id=1返回的string,不能转换成列名。

【问题讨论】:

  • 运行该查询时遇到的错误是什么?我似乎得到了正确的回答,但我可能误解了这个问题:)
  • @RocketDonkey 它返回字符串“type_1”的数量(按项目中的行数)
  • 明白了,我的错 - 发布了一些可能有用的东西(抱歉,如果我再次误解了)。

标签: mysql


【解决方案1】:

您可能希望看到this question 的答案,我相信这就是您想要完成的。简而言之,答案建议使用准备好的语句来模拟 eval() 式的功能。在您的情况下,这可能有效(您可以查看 SQLFiddle here:

SELECT transaction_type FROM orders WHERE id=1 into @colname;
SET @table = 'items';
SET @query = CONCAT('SELECT ',@colname,' FROM ', @table);

PREPARE stmt FROM @query;
EXECUTE stmt;

我不会声称自己是工作中的基本机制方面的任何专家,但根据 cmets,它似乎实现了目标。同样,这是从另一个答案中采用的,所以如果它有效,请确保 +1 :)

【讨论】:

    【解决方案2】:

    问题是 select transaction_type 从返回的字符串 id=1的订单,不能转换成列名

    你必须像这样PIVOTorders 表的transaction_type 列的值:

        SELECT 
          id,
          MAX(CASE WHEN transaction_type = 'type_1' THEN 1 END) Type1,
          MAX(CASE WHEN transaction_tyep = 'type_2' THEN 2 END) type2
        FROM orders
        GROUP BY id
    

    那么你可以像这样JOIN两张表:

    SELECT i.id - what do you want to select
    FROM items i
    INNER JOIN
    (
        SELECT 
          id,
          MAX(CASE WHEN transaction_type = 'type_1' THEN 1 END) Type1,
          MAX(CASE WHEN transaction_tyep = 'type_2' THEN 2 END) type2
        FROM orders
        GROUP BY id
    ) o ON i.type_1 = o.type1 AND i.type_2 = o.type2 -- you can add more conditions
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 2014-05-24
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多