2014-12-23 27 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;