sql server - SQL query: How to select record from other table where no record exist or count = 0 (conditional) -


i had 2 tables:

table 1: staffdb

sid | name 1   | peter 2   | mary 3   | john 

table 2: employment history (staff have more 1 records)

histid | sid | positionid | iscurrent | startdate  | enddate   1      | 1   | 123        | 0         | dd-mm-yyyy | dd-mm-yyyy   2      | 1   | 221        | 1         | dd-mm-yyyy |   3      | 2   | 434        | 0         | dd-mm-yyyy | dd-mm-yyyy 

for example, in table 2.

peter (sid=1) had 2 records, 2nd record current record (iscurrent=1)    mary (sid=2) had 1 non current record    john (sid=3) don't have record 

how can write sql query select staff don't have employment history or don't have current record (iscurrent=1)

for above example, should returns mary , john.

thanks

use left join , check null primary key on joined table:

select staffdb.* staffdb left join employmenthistory on staffdb.sid = employmenthistory.sid   , employmenthistory.iscurrent = 1 employmenthistory.histid null 

or use exists - possibly more performant, although not readable (subjective):

select * staffdb not exists (select 1 employmenthistory                    employmenthistory.sid = staffdb.sid                   , employmenthistory.iscurrent = 1) 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -