MySQL:拆分字符串 SQL 以在 WHERE 子句中使用

发布于 2024-11-09 01:18:18 字数 547 浏览 0 评论 0原文

我正在寻找一种在 JasperReport 中使用 IN 关键字的方法。我的查询如下所示:

SELECT * FROM table_name WHERE CID IN (145,45, 452);

在 jasper 报告中,我可以设置它;

SELECT * FROM table_name WHERE CID IN ($P{MY_CIDS});

在我的 Java 中,我会将 $P{MY_CIDS} 作为 String 发送,因此我的查询将类似于

SELECT * FROM table_name WHERE CID IN ("145,45, 452");

我的问题是如何在 SQL 中进行转换 "145, 45, 452" 到有效查询,因此它将分别考虑每个值 145, 45, 452

所有帮助是赞赏。

I am looking for a way to use the IN keyword in JasperReport. My query looks like:

SELECT * FROM table_name WHERE CID IN (145,45, 452);

following that in jasper report I can setup this;

SELECT * FROM table_name WHERE CID IN ($P{MY_CIDS});

and from my Java I would send $P{MY_CIDS} as a String, so my query will look like

SELECT * FROM table_name WHERE CID IN ("145,45, 452");

My questions is how to transform in SQL "145,45, 452" to a valid query so it would take into consideration each value separately 145, 45, 452

All help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

初相遇 2024-11-16 01:18:18
WHERE FIND_IN_SET(CID, "145,45,452")

但这个查询总是会导致表全扫描。因此,我建议您重写代码并使用正确的 IN (A, B, C) 语法。

WHERE FIND_IN_SET(CID, "145,45,452")

But this query will always cause table fullscan. So I suggest you to rewrite your code and use proper IN (A, B, C) syntax.

佞臣 2024-11-16 01:18:18

你有两个选择。更常见的是像这样重写你的查询:

SELECT * FROM table_name WHERE CID IN (?, ?, ?, ..., ?);

我不确定另一个对于 MySQL 是否有效,但它在 PostgreSQL 中工作得很好。就是使用一个不可变的函数将字符串解析为一组整数,而是使用:

SELECT * FROM table_name WHERE CID IN (split_to_int(?));

You've two options. The more common, is to rewrite your query like this instead:

SELECT * FROM table_name WHERE CID IN (?, ?, ?, ..., ?);

I'm not sure the other is valid for MySQL, but it works fine in PostgreSQL. It is to use an immutable function that parses the string into a set of integers, and instead use:

SELECT * FROM table_name WHERE CID IN (split_to_int(?));
々眼睛长脚气 2024-11-16 01:18:18
SELECT * FROM table_name WHERE CID IN ($P!{MY_CIDS});

只需使用

$P!{MY_CIDS}

($P 和 {MY_CIDS} 之间的感叹号)即可。

Jasper 现在将像这样连接字符串:

"SELECT * FROM table_name WHERE CID IN ("
+"145,45,452"
+")";

导致:

SELECT * FROM table_name WHERE CID IN (145,45,452);

我花了很长时间才得到它,但现在它对我有用。”

SELECT * FROM table_name WHERE CID IN ($P!{MY_CIDS});

Just use

$P!{MY_CIDS}

(exclamation mark between $P and {MY_CIDS}).

Jasper will now concatinate the Strings like this:

"SELECT * FROM table_name WHERE CID IN ("
+"145,45,452"
+")";

resulting in:

SELECT * FROM table_name WHERE CID IN (145,45,452);

Took me a long time to get that but now it works for me."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文