多個條件數組查詢寫法:
$User = new UserModel();
$map['id'] = array('neq',1);
$map['name'] = 'yuanye';
$User->where($map)->select();
查詢“或”條件(_logic)
$where['name'] = array('like', '%
yuauye%');
$where['title'] = array('like','%
yuauye%');
$where['_logic'] = 'or';
$User->where($where)->select();
結果爲:( name like '%yuauye%') OR ( title like '%yuauye%')
如果需要使用字符串模式查詢使用方法
$User = new UserModel();
$map['_string'] = 'status=1 AND score>10';
$User->where($map)->select();
字符串模式查詢(_string)查詢多個“與”條件中嵌套“與”條件使用,例如:
$User = M("User"); // 實例化User對象
$map['id'] = array('neq',1);
$map['name'] = 'ok';
$map['_string'] = 'status=1 AND score>10';
$User->where($map)->select();
結果爲:( `id` != 1 ) AND ( `name` = 'ok' ) AND ( status=1 AND score>10 )
where between查詢,例如查詢某一個時間段內的數據,用法如下:
$where['create_time']=array('between',[$startTime,$endDate]);
使用數組格式的時候 between後面需要使用數組[$startTime,$endDate]
where in查詢,需要區分兩種情況,
in後面接的是數值數組
使用的是數值數組:array('in','1,5,8');
in 字符數組,使用字符數組的時候 ,後面的數組查詢條件需要拼接
$vinarr1 = '';
for ($i = 0; $i < count($vinarr); $i ++) {
$vinarr1 = $vinarr1 . "'" . $vinarr[$i] . "',";
}
$sqlBinds = "fvin in(" . $vinarr1 . "'')";
$sqlm = 'select MAX(accumula_time) as MaxaccumulaTime, MIN(accumula_time) as MinaccumulaTime,fvin , ltime as time from forklift_location WHERE ' . $sqlBinds . ' and ltime >= ? and ltime < ? group by fvin';
$sqlBinds = array(
$preDays,
$nowDate
);
$resultm = $this->forkliftLocation->query($sqlm, $sqlBinds);
代碼的使用出處來自查詢單輛叉車一個月內的平均工作時長,getmonthaverage
原生的sql
修改查詢的字段,將查詢的字段拼接處理後再查詢出,例如使用as當成新需要的字段
select 姓名, 工資, 面積, 金額, (工資+金額/1000) as 實發工資 from 職工,倉庫, 訂購單 where 職工.職工號=訂購單.職工號 and 職工.倉庫號=倉庫.倉庫號
全連接查詢
除滿足連接條件的記錄顯示外,兩張表中的不能滿足條件的記錄也顯示在查詢結果集中
[sql] view plain copy
select 姓名,城市 from 倉庫 full join 職工 on 職工.倉庫號=倉庫.倉庫號 and 城市 is not null and
姓名 like '%王%';
主要將兩個或者更多個查詢的結果組合爲單個結果集,該結果集包含聯合查詢中的全部查詢的全部行
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京'
union
select 倉庫號 from 職工 where 工資>2000
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京'
union
select 倉庫號 from 職工 where 工資>2000
select distinct 倉庫.倉庫號 from 倉庫, 職工 where 倉庫.倉庫號=職工.倉庫號 and (城市='北京' or 工資>2000)
使用union all 保留重複行
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京'
union all
select 倉庫號 from 職工 where 工資>2000
交運算(intersect)
可以將兩個select語句的查詢結果通過交運算合併成一個查詢結果
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京'
intersect
select 倉庫號 from 職工 where 工資>2000
[sql] view plain copy
- select distinct 倉庫.倉庫號 from 倉庫, 職工 where 城市='北京' and 倉庫.倉庫號=職工.倉庫號 and 工資>2000
差運算(except)
可以計算兩個select查詢結果之間的數據差,即返回在一個查詢結果中存在,但在另一個查詢結果中不存在的所有行。
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京'
except
select 倉庫號 from 職工 where 工資>2900
[sql] view plain copy
select 倉庫號 from 倉庫 where 城市='北京' and 倉庫號 not in(select 倉庫號 from 職工 where 工資>2900)