简体   繁体   English

JDBC-一个查询以返回单独的结果组

[英]JDBC - one query to return separate groups of results

I have a table that looks like this: Col: A (string), B (int), C(string) 我有一个看起来像这样的表: Col: A (string), B (int), C(string)

I want to be able to get rows where A matches either regex foo or regex bar . 我希望能够获得A匹配regex foo或regex bar Currently, I perform two queries: 当前,我执行两个查询:

SELECT * FROM myTable WHERE A LIKE foo and SELECT * FROM myTable WHERE A LIKE bar SELECT * FROM myTable WHERE A LIKE fooSELECT * FROM myTable WHERE A LIKE bar

I am confident that there will be no duplicates between these result sets. 我相信这些结果集之间不会重复。

I would like to be able to get an equivalent result by running a single query, so that I don't have to scan the table once for each acceptable value, for example: 我希望能够通过运行单个查询来获得等效的结果,这样我就不必为每个可接受的值扫描表,例如:

SELECT * FROM myTable WHERE A LIKE foo OR A LIKE bar

My problem is that such a query produces a result set with all the values jumbled together - I would then need to loop through using my own string comparison to separate the two. 我的问题是,这样的查询会产生一个结果集,其中所有值都混杂在一起-然后,我需要循环使用自己的字符串比较来将两者分开。 Furthermore, strings that match A LIKE foo can be very different, so I can't just group on A . 此外,与A LIKE foo匹配A LIKE foo字符串可能会非常不同,因此我不能仅对A分组。

Is there a way to perform a single traversal of the table (for efficiency's sake), but still get JDBC / SQL to do the work of separating the results into one group for A LIKE foo and another group for A LIKE bar ? 有没有一种方法可以执行表的单个遍历(为了提高效率),但是仍然可以通过JDBC / SQL来完成将结果分为A LIKE fooA LIKE bar

If you are confident that there would be no duplicates, run a UNION ALL with a discriminator: 如果您确信不会有重复项,请运行带有鉴别UNION ALL

SELECT 'foo' as which_regex, *
FROM myTable
WHERE A LIKE foo
UNION ALL
SELECT 'bar' as which_regex, *
FROM myTable
WHERE A LIKE bar

JDBC will run this as a single query, even though it has two parts. JDBC将其作为单个查询运行,即使它包含两个部分。 There will be an extra "discriminator" column called which_regex added to the result, which would contain string 'foo' or string 'bar' . 将在结果中添加一个额外的“ discriminator”列,该列称为which_regex ,其中包含字符串'foo'或字符串'bar' You can use this column to decide in what "bucket" to put each row of the result. 您可以使用此列来决定将哪个“存储桶”放入结果的每一行。

You could add an additional boolean column to the resultset and even sort by that. 您可以在结果集中添加一个额外的布尔列,甚至可以按此排序。

SELECT A LIKE foo AS group_foo, * FROM myTable WHERE A LIKE foo OR A LIKE bar ORDER BY 1;

The first column of the resultset then tells which group it belongs to (true for foo, false for bar) and it's easy to separate them when processing the resultset. 然后,结果集的第一列告诉它属于哪个组(对于foo为true,对于bar为false),并且在处理结果集时很容易将它们分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM