用于从2个表中获取记录的标量查询

时间:2014-11-18 12:21:49

标签: mysql

我有一个表作为tbl_employee,分别有列id,name,bco和wco。 bco和wco将int值作为其数据类型。

我有一个包含cid和country

列的表tbl_country

我想以

的形式获取记录
Name        Bco       WCO
==========================
Raj         India     USA

3 个答案:

答案 0 :(得分:0)

这需要加入tbl_country两次,如下所示。请注意,查询正在使用inner join,因此bcowco都应在country表中包含匹配的记录,否则只需使用left join

select
e.name,
c1.country as Bco,
c2.country as WCO
from tbl_employee  e
join tbl_country c1 on c1.cid = e.bco
join tbl_country c2 on c2.cid = e.wco

答案 1 :(得分:0)

SELECT tbl_employee.id,tbl_employee.name,tbl_country.countryName 
  as BCO,tbl_country.countryName as WCO 
FROM tbl_employee 
LEFT JOIN tbl_country ON tbl_country.id = tbl_employee.bco 
RIGHT JOIN tbl_country ON tbl_country.id = tbl_employee.wco

答案 2 :(得分:0)

试试这个:

SELECT tbl_employee.name AS name, lookup_bco.country AS Bco, lookup_wco.country AS WCO
FROM tbl_employee
INNER JOIN tbl_country AS lookup_bco ON tbl_employee.bco = lookup_bco.cid
INNER JOIN tbl_country AS lookup_wco ON tbl_employee.wco = lookup_wco.cid