SELECT db.id,db.name,payerDb.name FROM db
LEFT JOIN (SELECT * FROM db ) AS payerDb ON (db.payer=payerDb.id)
就這樣吧。有好幾種寫法。我只用其中一個
SELECT t.[id]
,t.[name]
,pt.[name] as payer
FROM [dbo].[table] as t
LEFT JOIN [dbo].[table] as pt
ON t.payer = pt.id
大概這樣(?
SELECT outtab.`id`, outtab.`name`, (SELECT intab.`name` FROM `[table_name]` AS intab WHERE intab.`id` = outtab.`payer`) AS 'payer' FROM `[table_name]` AS outtab
(我預設有兩個table長的一樣,分別叫table1、table2)
USE test;
SELECT table1.id,table1.name,table2.name FROM table1,table2
WHERE table1.payer = table2.id;
這是執行的結果:
小弟最近剛學SQL,想到這樣比較簡單的作法,有問題還請多指教,感謝!
SELECT tab.id, tab.name, ptab.name
FROM tab, tab as ptab
WHERE tab.payer = ptab.id;
將原先的資料表(tab) as 成 ptab 接著用 WHERE tab.payer = ptab.id 就能像目標Table一樣了