簡體   English   中英

如何在 sql 連接中使用別名

[英]How to use an alias in a sql join

我喜歡用案例創建一個變量:

case  when (a.exit_date='0001-01-01' and z.fermeture<>'0001-01-01') then z.fermeture
else a.exit_date
 end as final_exit_date,

在我得到一個 sql 加入之后:

select a.*,b.*

from   table1 as a
  left join table2 as b on (a.id=b.id and b.start <= a.exit_date and a.exit_date < b.end)

where a.id=28445

當我這樣做時,它會起作用。 但是我不想使用變量“a,exit_date”我想根據我創建的變量(final_exit_date)替換它:喜歡它:

select a.*,b.*

from   table1 as a
  left join table2 as b on (a.id = b.id and b.start <= final_exit_date and final_exit_date < b.end)

where a.id=28445

預先感謝您閱讀我!

當您在SELECT列表中創建帶有別名的表達式時,唯一允許您使用別名的地方是在ORDER BY子句中。 這讓 SQL 中的許多人感到沮喪,因為別名通常在WHERE子句或其他地方有用,但這是不可能的。

解決方案是您必須復制表達式而不是使用別名。

SELECT a.*,b.*
FROM table1 AS a
-- you will need the z table as well
LEFT JOIN table2 AS b ON (a.id=b.id and b.start <= 
CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END 
AND 
CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END < b.end)
WHERE a.id=28445

另一種選擇是使用公用表表達式 (CTE) 或子查詢,以便別名可用。 使用 CTE,它看起來像這樣:

;WITH records AS (
    SELECT a.*, CASE WHEN (a.exit_date='0001-01-01' AND z.fermeture<>'0001-01-01') THEN z.fermeture ELSE a.exit_date END AS final_exit_date
    FROM table1 AS a 
    LEFT OUTER JOIN otherTable AS z ON a.id = z.id -- whatever the condition is
) 
SELECT r.* b.* 
FROM records AS r 
LEFT JOIN table2 AS b ON r.id = b.id AND b.start<= r.final_exit_date AND r.final_exit_date < b.end

上面的查詢可能存在一些問題,因為您沒有包括表名或列(或者它們之間的關系),但是您應該能夠通過采用這兩種方法中的一種來創建可行的解決方案。

暫無
暫無

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

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