簡體   English   中英

將 WHERE 子句優先於 2 列

[英]Prioritize WHERE clause over 2 columns

我有一些桌子

CREATE TABLE some_table(row_id int, id_1 varchar, id_2 varchar, some_value varchar)

id_1 和 id_2 列可以是以下值之一 - 'a'、'b'、'c'、'd'。

樣本數據:

|row_id|id_1 |id_2 |some_value|
|  1   |  a  |  b  |  abcd    |
|  2   |  b  |  c  |  bcde    |
|  3   |  d  |  a  |  cdef    |
|  4   |  c  |  d  |  def     |
|  5   | null|  a  |  efg     |
|  6   |  b  | null|  fgh     |
|  7   |  c  | null|  ghi     |
|  8   | null|  d  |  hik     |
|  9   | null| null|  ikl     |     

我想要的結果:

|row_id|id_1 |id_2 |some_value|
|  1   |  a  |  b  |  abcd    |
|  2   |  b  |  c  |  bcde    |
|  3   |  d  |  a  |  cdef    |
|  5   | null|  a  |  efg     |
|  6   |  b  | null|  fgh     |    

我需要選擇行,如果:

  1. id_1 = 'a' 或 id_1 = 'b'
  2. 如果 id_1 不符合條件 1,則 id_2 = 'a' OR id_2 = 'b' 我知道我可以使用一些子查詢和聯合:
WITH a_or_b_values AS(
    SELECT * 
    FROM some_table
    WHERE id_1 = 'a' or id_1 = 'b'
        or id_2 = 'a' or id_2 = 'b'
),
id_1_values AS (
    SELECT *
    FROM some_table
    WHERE id_1 = 'a' OR id_1 = 'b'
) SELECT * 
FROM some_table
WHERE NOT EXISTS(SELECT row_id FROM id_1_values WHERE id_1_values.row_id = a_or_b_values.row_id)
UNION
SELECT * FROM id_1_values;

是否存在更高效/優雅的解決方案?

PS:我使用 Vertica/Postgres db,但這個問題更多的是關於邏輯 - 任何 db 的解決方案都是可以接受的

如果你想在結果集中一行,您可以使用order by和獲取一行:

select t.*
from t
where id_1 in ('a', 'b') or id_2 in ('a', 'b')
order by (case when id_1 in ('a', 'b') then 1 else 2 end)
offset 1 row fetch first one row only;

編輯:

對於您澄清的問題,我認為您只想:

select t.*
from t
where t.id_1 in ('a', 'b') or
      t.id_2 in ('a', 'b');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM