我将值存储在MySql表中,如下所示:
id content_id group_id value ================================================ 12274 251 5 4 GB, 512 MB RAM 12323 252 5 32 GB, 2 GB RAM 12372 253 5 8 GB, 2 GB RAM 12421 254 5 8 GB, 1 GB RAM 12470 255 5 8 GB, 1 GB RAM 12519 256 5 4 GB, 512 MB RAM
其中“值”列中包含内部存储器和移动式RAM的行,每行中都用逗号分隔,现在我要在“值”列中执行搜索结果,这将使我获得RAM“ 512 MB”和“ 2 GB”之间的所有行>
我如何在MySql中执行此操作?请帮助
答案 0 :(得分:4)
开始时是作为注释,但超出了可用空间。我们可以给您一个查询,但是它会很肿并且很丑。将表设计固定为这样会更好:
id content_id group_id value_low value_high
=========================================================
12274 251 5 0.512 4
12323 252 5 2 32
12372 253 5 2 8
12421 254 5 1 8
12470 255 5 1 8
12519 256 5 0.512 4
首先要了解的重点是,我们为存储范围的低端和高端分别设置了真实的列。第二,我们到处都使用一个统一的单位GB。考虑到这些更改,我们可以轻松编写您的查询:
SELECT *
FROM yourTable
WHERE value_high >= 2.0 AND value_low <= 0.512;
答案 1 :(得分:1)
以逗号分隔的值很难查询。
需要使用棘手的SQL将项目解析为记录,因此理想情况下,您应该像Tim Biegeleisen建议的那样进行规范化。
另外,当您拥有使用正则表达式的MySQL 8.0时,更容易实现。
查询
SELECT
#remove duplicates
DISTINCT
t.*
, TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)) AS tag
, CASE
WHEN LOCATE('GB', UPPER(TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)))) > 0
# return GB to MB calculated
THEN (TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)) + 0.00) * 1024
# return MB value
ELSE TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)) + 0.00
END AS MB_calculated
FROM (
SELECT
@number := @number + 1 AS number
FROM (
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row1
CROSS JOIN
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row2
CROSS JOIN
(SELECT @number:=0) AS init_user_params
)
)
AS numbers
CROSS JOIN t
WHERE
CASE
WHEN LOCATE('GB', UPPER(TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)))) > 0
# return GB to MB calculated
THEN (TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)) + 0.00) * 1024
# return MB value
ELSE TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.value, ',', numbers.number), ',', -1)) + 0.00
END BETWEEN 512 AND (2 * 1024)
结果
| id | content_id | group_id | value | tag | MB_calculated |
| ----- | ---------- | -------- | ---------------- | ---------- | ------------- |
| 12274 | 251 | 5 | 4 GB, 512 MB RAM | 512 MB RAM | 512 |
| 12323 | 252 | 5 | 32 GB, 2 GB RAM | 2 GB RAM | 2048 |
| 12372 | 253 | 5 | 8 GB, 2 GB RAM | 2 GB RAM | 2048 |
| 12421 | 254 | 5 | 8 GB, 1 GB RAM | 1 GB RAM | 1024 |
| 12470 | 255 | 5 | 8 GB, 1 GB RAM | 1 GB RAM | 1024 |
| 12519 | 256 | 5 | 4 GB, 512 MB RAM | 512 MB RAM | 512 |
请参阅demo