Mysql 如何在同一语句中组合like和between(laravel查询生成器/模型)
以下是电脑型号的HDD列(我知道它不是一种存储数据的好格式,但它已经像那样存储了) 我想从HDD列中提取存储在特定范围内的范围,例如,应输出120GB到1TB之间的fetch存储Mysql 如何在同一语句中组合like和between(laravel查询生成器/模型),mysql,sql,laravel,laravel-7,laravel-7.x,Mysql,Sql,Laravel,Laravel 7,Laravel 7.x,以下是电脑型号的HDD列(我知道它不是一种存储数据的好格式,但它已经像那样存储了) 我想从HDD列中提取存储在特定范围内的范围,例如,应输出120GB到1TB之间的fetch存储 4x1TBSATA2 2x120GBSSD 4x480GBSSD 我想知道是否有可能在同一个声明中合并like和between 我尝试了以下方法,但不起作用 select * from `server_details` where `HDD` between '%120GB%' and '%10TB%' selec
4x1TBSATA2
2x120GBSSD
4x480GBSSD
我想知道是否有可能在同一个声明中合并like和between
我尝试了以下方法,但不起作用
select * from `server_details` where `HDD` between '%120GB%' and '%10TB%'
select * from `server_details` where `HDD` between "Like '%120GB%'" and "LIKE '%10TB%'"
在数据库中的HDD列中,不应存储120GB、10TB等字母数字值,而应存储12010000等数字值。请尝试以下查询
$hdds = DB::table('server_details')
->whereBetween('HDD', [120, 10000])
->get();
不能在通配符查询中使用between。您可以编写一个正则表达式来匹配所需的内容,例如:
select * from `server_details` where `HDD` regexp '1[2-9]\dGB|[2-9]\d\dGB|\dTB|10TB'
但正如你所看到的,这是一个基于你所写内容的非常具体的表达式,每个不同的限制都需要一个不同的表达式
有很多方法可以生成这样的表达式,但我找不到PHP代码(通过一些非常基本的谷歌搜索)
另一个解决方案(我个人建议)是将容量添加为一个单独的列:
迁移当前表:
class AddCapacityColumnMigration extends Migration {
public function up()
{
Schema::table('computers', function (Blueprint $table) {
$table->bigInt('capacityMB')->nullable();
});
Computer::chunk(100, function ($computers) {
foreach ($computers as $computer) {
if (preg_match('/(\d+)x(\d+)(M|G|T)B/',$computer->HDD,$m) {
$capacity = $m[1];
$capacity *= $m[3] === 'M' ? 1 : ($m[3] === 'G' ? 1000 : 1000000 );
$computer->capacityMB = $capacity * $m[2];
$computer->save();
}
}
});
}
然后,您可能需要在模型中添加创建
和更新
事件,以确保始终设置新的capacityMB列。完成所有这些操作后,您的查询非常简单:
select * from `server_details` where `capacityMB` between 120000 and 10000000
如果只需要在SQL中执行,请提取大小部分,将其转换为数字,然后进行比较
select *,
cast(`HDD` as unsigned)*
cast(substr(`HDD`,LOCATE('x',`HDD`)+1) as unsigned)*
(case when`HDD` LIKE '%TB%' then 1000 else 1 end) as GB
from `server_details`
where
cast(`HDD` as unsigned)*
cast(substr(`HDD`,LOCATE('x',`HDD`)+1) as unsigned)*
(case when`HDD` LIKE '%TB%' then 1000 else 1 end)
between 120 and 10000;
select *,
cast(`HDD` as unsigned)*
cast(substr(`HDD`,LOCATE('x',`HDD`)+1) as unsigned)*
(case when`HDD` LIKE '%TB%' then 1000 else 1 end) as GB
from `server_details`
where
cast(`HDD` as unsigned)*
cast(substr(`HDD`,LOCATE('x',`HDD`)+1) as unsigned)*
(case when`HDD` LIKE '%TB%' then 1000 else 1 end)
between 120 and 10000;