![](/img/trans.png)
[英]JOIN SQL results from same table in one row and use values as column name
[英]SQL JOIN row from different table with the same values
所以我有這張桌子
code | name
-----------------
1 | abc
2 | asd
3 | aws
然后我有這個新表用於交易
code | new_code
---------------------
1 | 2
2 | 3
我想獲得如下所示的視圖:
code | name | new_code | name |
---------------------------------------
1 | abc | 2 | asd |
2 | asd | 3 | aws |
我應該對此視圖使用哪種查詢。 謝謝
SELECT t.code, t.name, n.new_code, nt.name
FROM this_table t
INNER JOIN new_table n ON t.code = n.code
INNER JOIN this_table nt ON n.new_code = nt.code
您的案例的架構。
SELECT * INTO #TAB1 FROM (
SELECT 1 CODE ,'ABC' NAME
UNION ALL
SELECT 2,'ASD'
UNION ALL
SELECT 3,'AWS'
) AS A
SELECT * INTO #TAB2 FROM (
SELECT 1 AS CODE, 2 AS NEW_CODE
UNION ALL
SELECT 2,3
)AS A
而下一個是解決方案
SELECT T1.*, T2.NEW_CODE, T3.NAME FROM
#TAB1 T1
INNER JOIN #TAB2 T2 ON T1.CODE = T2.CODE
INNER JOIN #TAB1 T3 ON T2.NEW_CODE = T3.Code
您也可以使用這種方式
SELECT
nt.code,
(SELECT name FROM first_table where code=nt.code) AS name,
nt.new_code,
(SELECT name FROM first_table where code=nt.new_code) AS name
new_table nt
SELECT table1.code, table1.name, table2.new_code, table2.name
FROM table1
JOIN table2 ON table1.code = table2.code;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.