所以我有一点 mysql 正在努力解决。我的目标是将分组的计数插入到主记录中,以告诉我每个状态在记录的相关表中有多少,因此结果可能如下所示:
| id | name | count1 | count2 |
------------------------------------
| 1 | primary 1 | 5 | 3 |
| 1 | primary 2 | 2 | 7 |
select * from primaryTable
left join (
select
case
when relationTable.relation_status_id = 1
then count(*)
END as count1,
case
when relationTable.relation_status_id = 2
then count(*)
END as count2
) relationTable
on relationTable.primary_id = primaryTable.id
我尝试使用子查询来完成它,这很有效,但需要按计数进行选择,我正在努力避免这种情况。
向子查询添加分组依据导致返回多行的错误。
最佳答案
在子查询中,与其在 CASE
中聚合 COUNT()
,您可能更容易使用 SUM()
将 bool 比较的结果(0
或 1
)以返回类似于计数的结果。
SELECT
primaryTable.*,
count1,
count2
FROM
primaryTable
JOIN (
SELECT
primary_id,
-- Sum the results of a boolean comparison
SUM(relation_status_id = 1) AS count1,
SUM(relation_status_id = 2) AS count2
FROM relationTable
-- Group in the subquery
GROUP BY primary_id
-- Join the subquery to the main table by primary_id
) counts ON primaryTable.primary_id = counts.primary_id
请注意,因为 MySQL 将 bool 值视为 0 或 1,比较 relation_status_id = 1
返回 1 或 0。并非每个 RDBMS 都支持上述语法。为了更便携,您需要在 SUM()
中使用 CASE
来显式返回整数 1 或 0。
SUM(CASE WHEN relation_status_id = 1 THEN 1 ELSE 0 END) AS count1,
SUM(CASE WHEN relation_status_id = 2 THEN 1 ELSE 0 END) AS count2
您最初的尝试存在一些语法问题。主要是,它没有 FROM
子句,这导致 MySQL 认为它应该被视为一个标量值,然后提示它返回了不止一行。
关于mysql - 在 mysql 中找不到表或列与选择和案例连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676746/