2014-12-23 29 views
2

我有一個表TBLCUTOMERS具有以下字段:如何在MYSQL查詢中添加子查詢?

- cutomerid 
- customername 
- customerphone 

我有以下字段另一個表TBLTRANSACTIONS:

- transactionid 
- customerid (foreign key to table above) 
- transactiondetail 
- transactionamount 

我有一個查詢從tbltransactions獲得所有交易:

"select * from tbltransactions"; 

我怎樣才能在其中的子查詢,使得我的客戶名從TBLCUSTOMERS對上述查詢中的每個CUSTMERID?

期待輸出:

- transactionid 
- customername (from tblcustomers) 
- transactiondetail 
- transactionamount 

請注意,我是新來的MySQL。謝謝

+0

您可以使用連接查詢將這項工作?我的意思是,如果我給你一個連接查詢不是子查詢會好嗎? –

+0

當然!我只對結果感興趣。 –

+0

你允許我們使用JOIN嗎? –

回答

1
select tt.transactionid ,tc.customername,tt.transactiondetail,tt.transactionamount from tbltransactions tt,TBLCUTOMERS tc where tt.customerid=tc.cutomerid 

我認爲這將解決您的目的。爲你的參考ckeck link

0

它不是子查詢,我們使用連接爲此目的。

類似的東西。

Select tt.*, c.customername 
from 
tbltransactions as tt 
left join TBLCUTOMERS as c 
on tt.customerid = c.customerid 

而且使用左連接或右連接或內部聯接,按您的要求的條件

+0

爲什麼這個外部連接是必需的,我不明白。 –

+0

作爲外連接稍快於內連接 – KoolKabin

0

試試這個:

SELECT T.transactionid, C.customername, T.transactiondetail, T.transactionamount 
FROM TBLTRANSACTIONS T 
INNER JOIN TBLCUTOMERS C ON T.cutomerid = C.cutomerid;