“Unknown column in 'field list'” when prepared statement's placeholder is in subquery

↘锁芯ラ 提交于 2019-11-29 15:16:14

Your latest edit made the question very clear, so I'll attempt an answer: the cause of this difference is the placeholder.

As documented here, placeholders can only be used in certain places in the query. In particular:

Parameter markers can be used only where data values should appear, not for SQL keywords, identifiers, and so forth.

Now you might have noticed that SELECT ? as x prepares fine, but not SELECT nr.x FROM (SELECT ? AS x) AS nr. Why is that? Well this is best explained by an anonymous author on PHP's doc, so let me copy/paste:

There is a common misconception about how the placeholders in prepared statements work: they are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.

So simply put: because you are using a placeholder in a subquery in the FROM clause, MySQL cannot calculate the execution plan of the query.

In other words, since your query will always change, there is not "template" that can be prepared for it.

Therefore if you really want to use this query, you need to use a normal (non-prepared) query, or turn back on PDO's emulated prepared statements.

That being said, please, do consider the various alternatives offered in the comments section. There are much better solutions for what you are trying to achieve.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!