MySql需要一个查询来从一行中的表中检索多个字段

时间:2011-11-30 14:56:09

标签: mysql sql

我在MySql数据库中有以下表格:

**EmpInfo**

ID               Name                Address
--------------------------------------------------------
10001            Rocky Silva         11, satellite street


**EmpContact**  notion ( M for mobile number and L for Landline number)

ID               Phone               Type
--------------------------------------------------------
10001          909099925               M
10001          20222525                L   

我想以这样一种方式创建一个视图,使它在一行中返回我(在笛卡尔积之后不是双行):

10001        Rocky Silva       11, satellite street  909099925      20222525

任何人都可以帮我查询吗?我尝试了不同的连接,但没有运气;我想我错过了什么......

5 个答案:

答案 0 :(得分:4)

SELECT id, name address, GROUP_CONCAT(phone) as phones
FROM EmpInfo
JOIN EmpContact USING (id)
GROUP BY id;

答案 1 :(得分:2)

尝试:

select i.ID,
       i.Name,
       i.Address,
       cm.Phone as Mobile,
       cl.Phone as Landline
from EmpInfo i
left join EmpContact cm on i.ID = cm.ID and cm.Type = 'M'
left join EmpContact cl on i.ID = cl.ID and cl.Type = 'L'

答案 2 :(得分:1)

试试这个 -

SELECT e.*, MAX(IF(ec.Type = 'M', ec.Phone, NULL)) M, MAX(IF(ec.Type = 'L', ec.Phone, NULL)) L FROM EmpInfo e
  LEFT JOIN EmpContact ec
    ON e.ID = ec.ID
GROUP BY e.ID;

答案 3 :(得分:1)

使用group_concat函数

SELECT i.id, i.name, i.address, group_concat(c.phone)
from empInfo i, empContact c
where c.id = i.id
group by i.id,i.name,i.address

这将为您提供以逗号分隔的所有手机。如果您想要单独的列,请执行此操作

SELECT i.id, i.name, i.address,
GROUP_CONCAT(if (Type = 'M', phone, NULL)) AS 'Mobile', 
GROUP_CONCAT(if (Type = 'L', phone, NULL)) AS 'Landline', 
from empInfo i, empContact c
where c.id = i.id
group by i.id,i.name,i.address

答案 4 :(得分:0)

如果您知道要合并的元素数量,您可以执行以下操作(适用于2):

SELECT EmpInfo.*, EC1.Phone, EC2.Phone from EmpInfo, EmpContact as EC1, EmpContact is EC2
WHERE EmpInfo.ID = EC1.ID and EmpInfo.ID = EC2.ID and EC1.Phone < EC2.Phone

这假设每个ID只有2部电话