在MySQL中考虑以下示例。
DECLARE myText TEXT;
SET myText = "myColumn";
SELECT * FROM myTable WHERE myText = "myValue";
在上面的场景中,它不会选择任何列,因为myText的值永远不会是“myValue”。但是,我真正想要做的是将myText的值解释为查询的一部分,以便它执行的最终查询是:
SELECT * FROM myTable WHERE myColumn = "myValue";
我该怎么做?
答案 0 :(得分:1)
SET @myText = "myColumn";
SET @s = CONCAT('SELECT * FROM myTable WHERE ', @myText, ' = "myValue" ');
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;