如何对字符串中的 ID 运行查询?
我有一个包含此列的表 A:
IDS(VARCHAR)
1|56|23
我需要运行此查询:
select TEST from TEXTS where ID in ( select IDS from A where A.ID = xxx )
TEXTS.ID
是一个 INTEGER
。如何将字符串 A.IDS 拆分为多个整数以进行连接?
必须在 MySQL 和 Oracle 上运行。 SQL99首选。
I have a table A with this column:
IDS(VARCHAR)
1|56|23
I need to run this query:
select TEST from TEXTS where ID in ( select IDS from A where A.ID = xxx )
TEXTS.ID
is an INTEGER
. How can I split the string A.IDS into several ints for the join?
Must work on MySQL and Oracle. SQL99 preferred.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您不应该将这样的数据存储在列中。您应该将其拆分为一个单独的表,然后您就会有一个正常的连接,而不是这个问题。
话虽如此,您需要做的是以下操作:
|
(您的分隔符)字符填充它,在它之前和之后(我会告诉你为什么下面)LIKE
这会运行缓慢!
这是执行您想要的 SQL (假设所有运算符和函数都在您的 SQL 方言中工作,您不会说这是什么类型的数据库引擎):
您需要在前后用分隔符填充两者的原因是:如果您是寻找数字 5?您需要确保它不会仅仅因为它包含数字而意外地适合
56
数字。基本上,我们会这样做:
如果 A 中只有 1 行,如果你这样做,它可能会运行得更快(但我不确定,你需要测量它):
如果你的 A 中有很多行
TEXTS
表中,值得努力添加代码来生成适当的 SQL,方法是首先从A
表中检索值,使用IN 构造适当的 SQL
并使用它:这将运行得更快,因为现在它可以在此查询上使用索引。
如果您将 A.ID 作为一列,并将值作为单独的行,则执行查询的方式如下:
这将比前一个查询运行得稍慢,但在前一个查询中,您必须首先检索
A.IDS
,构建查询,并冒着生成必须编译的新执行计划的风险。First of all, you should not store data like this in a column. You should split that out into a separate table, then you would have a normal join, and not this problem.
Having said that, what you have to do is the following:
|
(your separator) character, before it, and after it (I'll tell you why below)LIKE
on itThis will run slow!
Here's the SQL that does what you want (assuming all the operators and functions work in your SQL dialect, you don't say what kind of database engine this is):
The reason why you need to pad the two with the separator before and after is this: what if you're looking for the number 5? You need to ensure it wouldn't accidentally fit the
56
number, just because it contained the digit.Basically, we will do this:
If there is ever only going to be 1 row in A, it might run faster if you do this (but I am not sure, you would need to measure it):
If there are many rows in your
TEXTS
table, it will be worth the effort to add code to generate the appropriate SQL by first retrieving the values from theA
table, construct an appropriate SQL withIN
and use that instead:This will run much faster since now it can use an index on this query.
If you had A.ID as a column, and the values as separate rows, here's how you would do the query:
This will run slightly slower than the previous one, but in the previous one you have overhead in having to first retrieve
A.IDS
, build the query, and risk producing a new execution plan that has to be compiled.