[英]Count distinct values with SELECT query results with error
I have a weird situation. 我有一个奇怪的情况。 I need to select all data from table name with distinct values from other table.
我需要从表名称中选择所有数据,并从其他表中选择不同的值。
Here is database scheme of database that I need to get distinct values: 这是我需要获取不同值的数据库的数据库方案:
When I run both queries without INNER JOIN they run without error but when I use INNER JOIN I got error 当我在不使用INNER JOIN的情况下运行两个查询时,它们都将运行而没有错误,但是当我使用INNER JOIN时却出现了错误
This is query that I used: 这是我使用的查询:
SELECT * FROM `todo`
INNER JOIN
SELECT `task`.`status`,COUNT(*) as count FROM `task`
ON `todo`.`id`=`task`.`id_list` WHERE `todo`.`user_id` = 43
As you can see I need to get total count of status column from other table. 如您所见,我需要从其他表中获取状态列的总数。 Can it be done using one single query or do I need to run two querys to get data...
可以使用一个查询完成,还是需要运行两个查询来获取数据...
You need to wrap the join In parenthesis 您需要将连接括起来
SELECT td.*, t.*
FROM `todo` td
JOIN
( SELECT `status`, SUM(status=0) as status_0, SUM(status=1) as status_1 , id_list
FROM `task`
GROUP BY id_list
) t ON td.id= t.id_list
WHERE td.user_id = 43
You can do this in one query. 您可以在一个查询中执行此操作。 Even without a subquery:
即使没有子查询:
SELECT ta.status, COUNT(*) as count
FROM todo t INNER JOIN
task ta
ON t.id = ta.id_list
WHERE t.user_id = 43
GROUP BY ta.status;
EDIT: 编辑:
If the above produces what you want, then you probably need: 如果以上内容满足您的要求,则您可能需要:
SELECT t.*, ta.status, taa.cnt
FROM todo t INNER JOIN
task ta
ON t.id = ta.id_list INNER JOIN
(SELECT count(*) as cnt, ta.status
FROM task ta
GROUP BY ta.status
) taa
on ta.status = taa.status
WHERE t.user_id = 43 ;
You seem to want a summary at the status
level, which is only in task
. 您似乎想要
status
级别的摘要,仅在task
。 But you want the information at the row level for todo
. 但是您想要行级的信息
todo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.