将字符串动态转换为列名称。 MySQL的

时间:2012-11-08 05:00:40

标签: mysql

我有两张表: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;

因此,问题是string返回的select transaction_type from orders where id=1无法转换为列名。

2 个答案:

答案 0 :(得分:9)

您可能希望看到this question的答案,我相信这是您要完成的目标。简而言之,答案建议使用预准备语句来模拟eval() - esque功能。在您的情况下,这可能有用(您可以看到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;

我不会声称自己是工作中潜在机制的专家,但根据评论,它似乎达到了目标。同样,这是从另一个答案中采用的,所以如果它有效,请确保+1那个:)

答案 1 :(得分:0)

  

问题是select transaction_type从中返回的字符串   订单中id = 1,无法转换为列名

您必须PIVOT transaction_type表的orders列的值,如下所示:

    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