简体   繁体   中英

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

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 . But you want the information at the row level for todo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM