简体   繁体   中英

get records from child table having count greater than 0 in sql server

I have a query below.

select 
    *,
    (select COUNT(*) from Table2 hv where hv.CompanyID=hc.CompanyID) VacancyCount
from Table1 hc
where
    hc.Deleted = 0
order by hc.NameLang1, VacancyCount desc

It gives me the right records always.I just want to add one more clause here is that select only those records from Table1 which is having atleast one record in Table2.Currently it returns all records which is having 0 records in Table2.

Please help me to solve this problem.

Try This

SELECT 
    *,
    (SELECT COUNT(*) FROM Table2 hv WHERE hv.CompanyID=hc.CompanyID) VacancyCount
FROM Table1 hc
WHERE EXISTS (SELECT hv.CompanyID FROM Table2 hv WHERE hv.CompanyID=hc.CompanyID)
   AND hc.Deleted = 0
ORDER BY hc.NameLang1, VacancyCount DESC;

For More know about EXISTS http://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

If You would like to select only records from Table1 which is having atleast one record in Table2 maybe You can try to using Inner Join.

select 
    hc.*,
    COUNT(.....some column in hv to be count....) as VacancyCount 
from 
  Table1 hc
  INNER JOIN Table2 hv ON hc.CompanyID ON hv.CompanyID
where
    hc.Deleted = 0
GROUP BY (....group all your hc column here....)
order by hc.NameLang1, VacancyCount desc

This will return all data in table1 which is having atleast one record in Table2. If there's any rows in table1 which doesn't have record in Table2 then that rows will not shown.

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