简体   繁体   中英

MySQL Query - SELECT row count from other table

I have this table in my database

在此处输入图片说明

And I;m using this query:

SELECT cl.cl_id, cl.name, COUNT(*) 
FROM cl, st 
WHERE st.cl_id = cl.cl_id 
GROUP BY cl.cl_id 
ORDER BY cl.cl_id;

Because some cl_id value in st table not exits, the output just return where cl_id is on the st table. The query I need is like this:

SELECT cl.cl_id, cl.name 
FROM cl;

but implement this

SELECT COUNT(*) 
FROM st 
WHERE st.cl_id = cl.cl_id;

but if in st table doesn't have all value from cl_id the value return to 0.

Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. In your case, it would then be obvious that you need a LEFT JOIN :

SELECT cl.cl_id, cl.name, COUNT(st.cl_id) 
FROM cl LEFT JOIN
     st 
     ON st.cl_id = cl.cl_id 
GROUP BY cl.cl_id 
ORDER BY cl.cl_id;

(based on Juan's answer) Use LEFT JOIN and the COALESCE function, which returns the first non-null value from a list of arguments

SELECT 
  COALESCE(st.cl_id,0)
, COALESCE(st.name,'Name Not Found')
, COUNT(cl.cl_id) 
FROM cl 
LEFT JOIN st 
  ON st.cl_id = cl.cl_id 
GROUP BY COALESCE(st.cl_id,0) 
ORDER BY COALESCE(st.cl_id,0) ;

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