我試圖做一些靠不住的,但我想不出任何其他方式做到這一點:如何使用字段名作爲參數嵌套的select語句
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = field1)) as does_exist
FROM my_table
這顯然失敗了,因爲field1
在結果集創建時不存在。有誰知道如何做到這一點?
我試圖做一些靠不住的,但我想不出任何其他方式做到這一點:如何使用字段名作爲參數嵌套的select語句
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = field1)) as does_exist
FROM my_table
這顯然失敗了,因爲field1
在結果集創建時不存在。有誰知道如何做到這一點?
您可以使用左側加入:
select distinct on (t1.field1) t1.field1, t2.id is not null as does_exist
from my_table t1
left join another_table t2 on t2.id = t1.field1
但是您的查詢應該工作以及:
SELECT
my_table.field1 as field1,
(EXISTS (SELECT 1 FROM another_table WHERE id = my_table.field1)) as does_exist
FROM my_table
選擇 my_table.field1爲FIELD1, 情況another_table.ID 當空,則0
else 1 end do_exist FROM my_table left outer j OIN another_table上another_table.ID = my_table.field1
這裏1存在,且0不存在
假設'mytable.field1'實際上不具有相同的名稱爲'field1','ID = mytable的。 field1'? – Ryan
哇,這工作。 – dopatraman
完成什麼?你所展示的所有代碼都不能以你無法預料的方式工作,而這種方式應該不是它本應該工作的方式。 「失敗」是什麼意思?不要過分依賴你的猜測,因爲「因爲」。 – philipxy