mysql - MySQL Regexp 解决方案的 Multi-Like 查询
问题描述
我希望以下内容有意义。我的查询应该返回列中的字符串值(+ 或 - 5)size
不存在于其对应title
列中的所有行。
桌子:
--------------
| size | title|
--------------
| 50 | 50ml |
| 75 | 75ml |
| 75 | 50ml |
| 100 | 97ml |
--------------
控制器:
$data = [
'find_all_sizes' => $model
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size - 5, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size - 4, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size - 3, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size - 2, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size - 1, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size + 1, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size + 2, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size + 3, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size + 4, "%")')
->where('CONCAT(brand, " ", title) NOT LIKE CONCAT("%", size + 5, "%")')
->groupBy('id')
->findAll()
];
这很好用 - 但我猜可能有更好的方法通过使用正则表达式来做到这一点,这是我真正需要帮助的地方。
解决方案
你可以试试:
$data = [
'find_all_sizes' => $model
->where("abs(size - cast(replace(title, 'ml', '') as signed)) < 5")
->groupBy('id')
->findAll()
];
在 SQL 中,一个 select * 查询看起来像这样,假设ml
标题中唯一的文本不是数字:
select * from t
where abs(size - cast(replace(title, 'ml', '') as signed)) < 5;
+------+-------+
| size | title |
+------+-------+
| 50 | 50ml |
| 75 | 75ml |
| 100 | 97ml |
+------+-------+
如果您的标题也可以包含其他字符串,您可以创建一个类似此处指定的函数:如何从 MySQL 查询中的字符串中提取数值?然后运行
select * from t
where abs(size - cast(digits(title) as signed)) < 5;
你可能会侥幸逃脱
select * from t
where abs(size - cast(title as signed)) < 5;
或者
$data = [
'find_all_sizes' => $model
->where("abs(size - cast(title as signed)) < 5")
->groupBy('id')
->findAll()
];
推荐阅读
- reactjs - 使用 react-select 和 react-hook-form 返回正确的值
- c# - 插入垂直滚动条以查看选项卡项的内容
- botframework - 与 Microsoft Teams 集成时如何获取频道名称
- django - /account/ 处的 NoReverseMatch
- security - 这是一种可以接受的刷新 JWT 的方法吗?
- azure - 无法访问 azure devops 组织和 azure 门户
- azure - 前门显示服务器标头 Microsoft-IIS/10.0
- r - 输入`typ`不能在R中回收到大小
- angularjs - 当从 UI 中选中(选择)时,AngularJS 在控制器中接收复选框值 = false
- javascript - UnhandledPromiseRejectionWarning:需要数据和盐参数