mysql查询某数字在某字段以逗号隔开的字符里面
DB::connection()->enableQuerylog();
$brokeList = DB::table('broke')->where(['brand_id' => 1, 'firm_id' => 0])
->orWhere(function($query){
$query->where('brand_id', '=', 1)
->whereIn('firm_id', [1,2] );
})
->get();
$sql = DB::getQueryLog();
var_dump($sql);
sql打印结果:
array(1) {
[0]=>
array(3) {
["query"]=>
string(112) "select * from `bijia_broke` where (`brand_id` = ? and `firm_id` = ?) or (`brand_id` = ? and `firm_id` in (?, ?))"
["bindings"]=>
array(5) {
[0]=>
int(1)
[1]=>
int(0)
[2]=>
int(1)
[3]=>
int(1)
[4]=>
int(2)
}
["time"]=>
float(1)
}
}
笨方法:
SELECT
firm_id
FROM
`bijia_broke`
WHERE
(`brand_id` = 1 AND `firm_id` = 0)
OR (
`brand_id` = 1
AND `firm_id` IN (1)
)
查询结果:
firm_id
0
0
1,2
1
1,2,3
1,2
1,3,2
1
1
1,2,3
看似是很合理的查询sql,但是经过尝试之后发现,为啥不把0放在in的数组里面呢?于是乎。。
SELECT
firm_id
FROM
`bijia_broke`
WHERE
`brand_id` = 1
AND `firm_id` IN (0, 1)
查询结果:
firm_id
0
0
1,2
1
1,2,3
1,2
1,3,2
1
1
1,2,3
--------------------------------------
SELECT
firm_id
FROM
`bijia_broke`
WHERE
`brand_id` = 1
AND `firm_id` IN (1)
查询结果:
firm_id
1,2
1
1,2,3
1,2
1,3,2
1
1
1,2,3
-----------------------------------------
SELECT
firm_id
FROM
`bijia_broke`
WHERE
`brand_id` = 1
AND `firm_id` IN (1,2,3)
查询结果:
firm_id
2,1,3
1,2
1
2,1
1,2,3
1,2
1,3,2
3,2,1
1
2,1,3
1
1,2,3
-------------------------------------------------------------------
另外在网上也查到 另一种方法,我没去尝试,框架本身用不了这函数。
首先我们建立一张带有逗号分隔的字符串。
CREATE
TABLE
test(id
int
(6)
NOT
NULL
AUTO_INCREMENT,
PRIMARY
KEY
(id),pname
VARCHAR
(20)
NOT
NULL
,pnum
VARCHAR
(50)
NOT
NULL
);
然后插入带有逗号分隔的测试数据
INSERT
INTO
test(pname,pnum)
VALUES
(
'产品1'
,
'1,2,4'
);
INSERT
INTO
test(pname,pnum)
VALUES
(
'产品2'
,
'2,4,7'
);
INSERT
INTO
test(pname,pnum)
VALUES
(
'产品3'
,
'3,4'
);
INSERT
INTO
test(pname,pnum)
VALUES
(
'产品4'
,
'1,7,8,9'
);
INSERT
INTO
test(pname,pnum)
VALUES
(
'产品5'
,
'33,4'
);
查找pnum字段中包含3或者9的记录
mysql>
SELECT
*
FROM
test
WHERE
find_in_set(
'3'
,pnum)
OR
find_in_set(
'9'
,pnum);
+
----+-------+---------+
| id | pname | pnum |
+
----+-------+---------+
| 3 | 产品3 | 3,4 |
| 4 | 产品4 | 1,7,8,9 |
+
----+-------+---------+
2
rows
in
set
(0.03 sec)
本文链接二维码可以保存在本地:保存
http://shixiangcun.cc/index.php?c=index&id=43&m=articleDetailInfo
分类 Laravel | 浏览 (142988) | 赞 (0) | 踩 (0) | | 2016-05-20 19:23:20 |
相关文章
- Mac安装Swoole扩展phpize 时 Cannot find autoconf 解决方法
- mac下安装swoole扩展报错PHP Startup Unable to load dynamic library
- Laravel 数据库事务
- PHP贷款等额本息、等额本金计算月供还款计划公式
- Laravel 关闭过滤排除部分路由VerifyCsrfToken 验证
- Laravel Horizon监控Redis队列queue