MySQL - 操作数应包含 1 列

MySQL - Operand should contain 1 column(s)(MySQL - 操作数应包含 1 列)
本文介绍了MySQL - 操作数应包含 1 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我创建的系统上工作时,我尝试在我的项目中使用以下查询:

While working on a system I'm creating, I attempted to use the following query in my project:

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

":cat" 在我使用 PDO 时受我的 PHP 代码约束.2 是 ":cat" 的有效值.

":cat" is bound by my PHP code as I'm using PDO. 2 is a valid value for ":cat".

该查询虽然给了我一个错误:#1241 - 操作数应该包含 1 列"

That query though gives me an error: "#1241 - Operand should contain 1 column(s)"

让我难受的是,我认为这个查询没有问题.选择列,然后从另一个表中再选择两个,然后从那里继续.我就是想不通是什么问题.

What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can't figure out what the problem is.

是否有一个简单的解决方法,或者其他编写查询的方法?

Is there a simple fix to this, or another way to write my query?

推荐答案

您的子查询正在选择两列,而您正在使用它来投影一列(作为外部 SELECT 子句的一部分).在此上下文中,您只能从此类查询中选择一列.

Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.

考虑加入users 表;在从 users 中选择您想要的列时,这将为您提供更大的灵活性.

Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.

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

这篇关于MySQL - 操作数应包含 1 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)