sql中一對多的表結構,要根據多的一方進行查詢,返回一的那方的數據,這時候需要用到exists,比如:
create table class {
long id,
varchar(20) name
}
create table teacher {
long id,
varchar(20) name,
long class_id
}
一個班級有多個老師,查詢有叫"張三"老師的班級信息,下面是不用exists的簡單處理方式。
select c.* from class c left join teacher t on c.id = t.class_id
where t.name = '張三'
問題在哪裏:假如A班有兩個老師都叫張三,則會搜出兩個A班來,而A班只有一個班級,假如前臺頁面有分頁的話,會出現問題.
用exists來實現查詢一個班級:
select * from class c
where exists(select 1 from teacher t where t.class_id = c.id and t.name = '張三')
這時候,只會搜出一個班級來,問題是:<u>exists不會走索引,會造成全部掃描,假如表格數據量大的話,會造成查詢慢的問題</u>
解決方案
- 用group by 代替exists
select c.* from class c left join teacher t on c.id = t.class_id
where t.name = '張三' group by c.id
- 分成子查詢來處理
select * from class c
where c.id in (select class_id from teacher t where t.name = '張三')
這樣既可以用上索引,又可以解決分頁問題.