我有一个非常简单的表:
create table mydata (id integer, data character varying(255), a integer, b integer);
insert into mydata values
(1, 'both a and b not found', null, null),
(2, 'a=not found, b=20', null, 20),
(3, 'a=10, b=not found', 10, null),
(4, 'a=10, b=20', 10, 20),
(... more rows with unique combinations of a and b);
Run Code Online (Sandbox Code Playgroud)
我需要一个查询,对于 a 和 b 的任何值都只返回一行。
如果找到 a 和 b 的值,则应选择指定的行(在本例中为 id=4)。
如果未找到这些值,但有一行与 a 的值匹配并且在 b 列中为空,则该行应定义此特定 a 和未知 b 的默认值。同样,如果找到 b 但没有找到 a 并且存在具有 b 值且 a 列中为空的行,则这是该情况的默认值。
如果找不到这样的默认值,但在 a 列和 b 列中存在带有空值的行,则该行指定一般默认值。
最后,如果该行也不存在,则返回零行。
http://sqlfiddle.com/#!17/a5173/5
目前,我已经通过一些运行几个特定 sql 查询直到找到匹配项的 java 代码解决了这个问题,但我想有一种 sql 方法可以解决这个问题。请指教。
SELECT * FROM mydata
WHERE (coalesce(a, user_a), coalesce(b, user_b)) = (user_a, user_b)
ORDER BY a IS NULL, b IS NULL
LIMIT 1;
Run Code Online (Sandbox Code Playgroud)
这里user_a和user_b是您查询的值。
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |