SQL Select 在字符串上使用爆炸查询行
SQL Select query rows using explode on a string
我需要根据一行的一列中包含的 ID 查询 MariaDB 数据库。 “children”列中的 ID 是一个字符串,其中包含如下所示的连接数字:
123;32523;436;241;345;234;
... 或:
23;45;324;56;2141;5464;2342;
我需要一个查询,像这样:
Select * from testTbl WHERE ID in (Explode(";", Select children from testTbl WHERE ID = 1))
我需要查询 return ID = 1 行上的 children 列中的行。我要查找的内容等同于我假设的 分解命令。
试试这个:
Select *
from testTbl
WHERE ';' + (Select children from testTbl WHERE ID = 1) + ';' LIKE '%;' + CAST(ID AS varchar(20)) + ';%'
您不应将事物列表存储为分隔列表。以下是一些原因:
- 数字应存储为数字,而不是字符串。
- ID 应该与它们引用的表有外键关系。
- 列应包含单个信息项,而不是列表。
- SQL 具有用于存储列表的出色数据结构。它被称为 "table".
也就是说,有时您会被其他人非常糟糕的设计所困。如果是这样,你可以用 replace()
和 find_in_set()
:
做你想做的事
select t.*
from testtbl t2
where exists (select 1
from testtbl t2
where t2.id = 1 and
find_in_set(t.id, replace(t2.children, ';', ',')) > 0
);
我需要根据一行的一列中包含的 ID 查询 MariaDB 数据库。 “children”列中的 ID 是一个字符串,其中包含如下所示的连接数字:
123;32523;436;241;345;234;
... 或:
23;45;324;56;2141;5464;2342;
我需要一个查询,像这样:
Select * from testTbl WHERE ID in (Explode(";", Select children from testTbl WHERE ID = 1))
我需要查询 return ID = 1 行上的 children 列中的行。我要查找的内容等同于我假设的 分解命令。
试试这个:
Select *
from testTbl
WHERE ';' + (Select children from testTbl WHERE ID = 1) + ';' LIKE '%;' + CAST(ID AS varchar(20)) + ';%'
您不应将事物列表存储为分隔列表。以下是一些原因:
- 数字应存储为数字,而不是字符串。
- ID 应该与它们引用的表有外键关系。
- 列应包含单个信息项,而不是列表。
- SQL 具有用于存储列表的出色数据结构。它被称为 "table".
也就是说,有时您会被其他人非常糟糕的设计所困。如果是这样,你可以用 replace()
和 find_in_set()
:
select t.*
from testtbl t2
where exists (select 1
from testtbl t2
where t2.id = 1 and
find_in_set(t.id, replace(t2.children, ';', ',')) > 0
);