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中文網其他相關文章!