join :取兩個表的合集;
left join:左表的資料全部保留,然後增加右表與左表條件匹配的記錄。如下
select cc.* from cloud_groups as cg left join cloud_contacts as cc on cg.ou=cc.departmentNumber order by cast(cg.sort as int),cast(cc.sort as int) //先以部門排序,再以員工進行排序
效果:
(1)cloud_groups 的內的資料全部保留
(2)增加 cloud_contacts 表中 cg.ou=cc.departmentNumber 的記錄
right join: 與left join的效果正恰相反。右表的資料全部保留,然後增加與相應條件匹配的記錄。
示例:
//根據部門編碼獲取指定部門下員工的數量 -(NSString *)getStaffCount:(NSString *) code { NSString *strSql = [[NSString alloc]initWithFormat:@" select count(*) from(select * from cloud_contacts as cc left join cloud_groups as cg on cg.ou=cc.departmentNumber) where code like'%%%@%%'",code]; NSString *staffCount=nil; if([mysqlite openDatabase:@"ucab_db.db"]) { staffCount = [[mysqlite selectintBySQL:strSql] objectAtIndex:0]; [mysqlite closeDatabase]; } if (nil!=staffCount) { return staffCount; } else return @"0"; }
關鍵字:on 是兩個表連線查詢時的條件,用於篩選笛卡爾積得出臨時表。where 是對對臨時表進行再次查詢!