Query
SQL db查詢:如何添加新欄位並分配值
我有 3 個表格,如下面的螢幕截圖所示。我使用 UNION 創建了一個查詢,如下所示。
SELECT T1_ID AS ID, T1_NAME AS NAME, T1_ADD AS ADDRESS FROM Table1 UNION SELECT T2_ID AS ID, T2_NAME AS NAME, T2_ADD AS ADDRESS FROM Table2 UNION SELECT T3_ID AS ID, T3_NAME AS NAME, T3_ADD AS ADDRESS FROM Table3
我得到了下面的結果。
我的問題是,如何添加一個名為 TYPE 的列(欄位)並將值分配給查詢結果,但不更新現有的三個表以使其像下面的螢幕截圖一樣?
不是最優雅的解決方案,但要回答您的問題,您可以這樣做:
SELECT T1_ID AS ID, T1_NAME AS NAME, T1_ADD AS ADDRESS, 'ANIMAL' AS TYPE FROM Table1 UNION SELECT T2_ID AS ID, T2_NAME AS NAME, T2_ADD AS ADDRESS, 'HUMAN' AS TYPE FROM Table2 UNION SELECT T3_ID AS ID, T3_NAME AS NAME, T3_ADD AS ADDRESS, 'OBJECT' AS TYPE FROM Table3