Yii2 操作mysql-联合查询where使用总结

简单赋值
->where(“id=:id”, [
‘id’ => 1
])
AND查询
->where(“id=:id and pack_name=:pack_name”, [
‘:id’ => 1,
‘:pack_name’ => ‘com.famigo.sandbox’
])
#或者
->where([
‘and’,
‘id=:id’,
‘pack_name=:pack_name’
], [
‘:id’ => 1,
‘:pack_name’ => ‘com.famigo.sandbox’
])
#这两种程式等同于 id=1 AND pack_name=’com.famigo.sandbox’
OR查询
->where(“id=:id or pack_name=:pack_name”, [
‘:id’ => 1,
‘:pack_name’ => ‘com.famigo.sandbox’
])
#或者
->where([
‘or’,
‘id=:id’,
‘pack_name=:pack_name’
], [
‘:id’ => 1,
‘:pack_name’ => ‘com.famigo.sandbox’
])
#这两种程式等同于 id=1 OR pack_name=’com.famigo.sandbox’
AND OR 混合查询
->where([
‘and’,
‘display=:display’,
[
‘or’,
‘id=:id1’,
‘id=:id2’
]
], [
‘:display’ => 1,
‘:id1’ => 1,
‘:id2’ => 2
])
# 上面的程式等同于(display=1) AND ((id=1) OR (id=2))
IN查询
->where([
‘in’, ‘id’, [1, 3, 5, 6]
])
#上面程式等同于 id in (1, 3, 5, 6)

->where([
‘and’,
‘display=:display’,
‘lang=:lang’,
[
‘in’, ‘id’, [1, 3, 5, 6]
]
], [
‘:display’ => 1,
‘:lang’ => 2
])
#上面程式等同于 (display=1) AND (lang=2) AND (`id` IN (1, 3, 5, 6))
#更为麻烦点的例子
->where([
‘or’,
[
‘and’,
‘display=:display1’,
[
‘in’, ‘id’, [1, 3, 5, 6]
]
],
[
‘and’,
‘display=:display2’,
[
‘in’, ‘id’, [2, 4, 8, 9]
]
]
], [
‘:display1’ => 1,
‘:display2’ => 2,
])
#上面程式等同于((display=1) AND (`id` IN (1, 3, 5, 6))) OR ((display=2) AND (`id` IN (2, 4, 8, 9)))
NOT IN 查询
[php] view plain copy
->where([
‘not in’, ‘id’, [1, 2, 4, 3]
])
#上面程式等同于`id` NOT IN (1, 2, 4, 3)
复杂的使用方法和上述的IN是一样的,参考即可。
LIKE 查询
->where([
‘like’, ‘pack_name’, ‘%sandbox%’
])
#上面程式等同于`pack_name` LIKE ‘%sandbox%’

->where([
‘like’, ‘pack_name’, [
‘%sandbox%’,
‘com.famigo%’
]
])
#上面程式等同于`pack_name` LIKE ‘%sandbox%’ AND `pack_name` LIKE ‘com.famigo%’

->where([
‘or like’, ‘pack_name’, [
‘%sandbox%’,
‘com.famigo%’
]
])
#上面程式等同于`pack_name` LIKE ‘%sandbox%’ OR `pack_name` LIKE ‘com.famigo%’

->where([
‘or not like’, ‘pack_name’, [
‘%sandbox%’,
‘com.famigo%’
]
])
#上面程式等同于`pack_name` NOT LIKE ‘%sandbox%’ OR `pack_name` NOT LIKE ‘com.famigo%’

->where([
‘not like’, ‘pack_name’, [
‘%sandbox%’,
‘com.famigo%’
]
])
#上面程式等同于`pack_name` NOT LIKE ‘%sandbox%’ AND `pack_name` NOT LIKE ‘com.famigo%’
LIKE复杂的使用方法请参考IN,都是类似的

发表评论