MySQL 查询错误:“操作数应包含 1 列”
问题描述:
在执行一个连接多个表并包含子查询(从另一个表中选择列)的 MySQL 查询时,出现错误:“#1241 - Operand should contain 1 column(s)”。
查询:
<code class="language-sql">SELECT topics.id, topics.name, topics.post_count, topics.view_count, COUNT( posts.solved_post ) AS solved_post, (SELECT users.username AS posted_by, users.id AS posted_by_id FROM users WHERE users.id = posts.posted_by) FROM topics LEFT OUTER JOIN posts ON posts.topic_id = topics.id WHERE topics.cat_id = :cat GROUP BY topics.id</code>
错误原因:
错误发生是因为子查询从 users
表中选择了两个列(username
和 id
),而外部查询期望子查询只返回单个列。
解决方案:
有两个方法可以解决此错误:
修改子查询:
username
列或 id
列。连接 users
表:
posted_by
列直接将 users
表连接到 posts
表。这种方法在从 users
表中选择所需列时提供了更大的灵活性。修改后的查询:
使用子查询:
<code class="language-sql">SELECT topics.id, topics.name, topics.post_count, topics.view_count, COUNT( posts.solved_post ) AS solved_post, (SELECT users.username AS posted_by FROM users WHERE users.id = posts.posted_by) FROM topics LEFT OUTER JOIN posts ON posts.topic_id = topics.id WHERE topics.cat_id = :cat GROUP BY topics.id</code>
使用连接:
<code class="language-sql">SELECT topics.id, topics.name, topics.post_count, topics.view_count, COUNT( posts.solved_post ) AS solved_post, users.username AS posted_by, users.id AS posted_by_id FROM topics LEFT OUTER JOIN posts ON posts.topic_id = topics.id LEFT OUTER JOIN users ON users.id = posts.posted_by WHERE topics.cat_id = :cat GROUP BY topics.id</code>
以上是为什么我的 MySQL 查询返回'操作数应包含 1 列”以及如何修复它?的详细内容。更多信息请关注PHP中文网其他相关文章!