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

Tor*_*den 9 mysql

我有两张桌子:itemsorders

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

orders
--------------
id (int) | transaction_type enum ('type_1', 'type_2')
Run Code Online (Sandbox Code Playgroud)

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

select (select transaction_type from orders where id=1) from items;
Run Code Online (Sandbox Code Playgroud)

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

Roc*_*key 9

您可能希望看到这个问题的答案,我相信这是您要完成的任务.简而言之,答案建议使用预准备语句来模拟eval() - esque功能.在你的情况下,这可能工作(你可以在这里看到SQLFiddle :

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;
Run Code Online (Sandbox Code Playgroud)

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


Mah*_*mal 0

问题是 select transaction_type from orders where id=1 返回的字符串无法转换为列名

您必须 像这样设置表列PIVOT的值:transaction_typeorders

    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
Run Code Online (Sandbox Code Playgroud)

然后你可以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
Run Code Online (Sandbox Code Playgroud)