Postgresql

即使零行匹配,也讓 SELECT 返回一個常量值

  • April 1, 2021

考慮這個選擇語句:

SELECT *, 
      1 AS query_id 
FROM players 
WHERE username='foobar';

它返回query_id帶有值的列1以及玩家的其他列。

即使選擇沒有找到匹配的行,如何使上述 SQL 至少返回query_idof ?1

順便說一句,它是 PostgreSQL 8.4。

SELECT col1, 
      col2, 
      col3, 
      1 AS query_id 
FROM players 
WHERE username='foobar'
union all 
select null,
      null,
      null,
      1
where not exists (select 1 from players where username = 'foobar');

或者作為替代方案(可能更快,因為不需要第二個子選擇):

with qid (query_id) as (
  values (1)
) 
select p.*, 
      qid.query_id
from qid 
 left join players as p on (p.useranme = 'foobar');

您可以將上面的內容重寫為更“緊湊”的表示:

select p.*, 
      qid.query_id
from (values (1)) as qid (query_id)
 left join players as p on (p.useranme = 'foobar');

但我認為明確的 CTE ( with...) 更具可讀性(儘管這總是在旁觀者的眼中)。

引用自:https://dba.stackexchange.com/questions/41067