我有一个mysql数据库查询,我想采取并压缩成一行。输出目前是两行,只有两行。我首先得到两行的原因是因为总会有一个与我的结果相关联的主要和次要电话号码。
由于除了电话类型(ptype)和第二个电话号码之外,两行的所有数据都完全相同,因此我只想将这两列添加到最后一行。
我知道这可以做到,但我不记得该怎么做了。
以下是我正在使用的代码:
SELECT
c.name,
c.address1,
p.ptype,
p.phone
FROM
customer AS c
Inner Join customeremp AS e ON c.customer_id = e.customer_id
Inner Join customerphone AS p ON e.customer_seq = p.customer_seq
WHERE
c.customer_id = '1'
答案 0 :(得分:2)
您需要在电话桌上创建2个联接
SELECTc.name,
c.address1,
p.ptype,
p.phone,
p2.ptype,
p2.phone,
FROMcustomer AS cInner
Join customeremp AS e ON c.customer_id = e.customer_idInner
Join customerphone AS p ON e.customer_seq = p.customer_seq and p.pType = 1 (or whatever private means)
Join customerphone AS p2 ON e.customer_seq = p2.customer_seq and p2.pType = 2 (or whatever the other type is)
WHEREc.customer_id = '1'
编辑:此查询仅返回设置了两种手机类型的客户。如果它们是可选的,那么您应该考虑将连接更改为外连接
答案 1 :(得分:1)
select c.name,c.address1,primary.phone,secondary.phone
from customer c
join customeremp e
on c.customer_id = e.customer_id
join customerphone primary
on primary.ptype = 'primary'
and e.customer_seq = primary.customer_seq
join customerphone secondary
on secondary.ptype = 'secondary'
and e.customer_seq = secondary.customer_seq
where c.customer_id = '1'
答案 2 :(得分:0)
试试这个:
SELECT
c.name,
c.address1,
IF(p.ptype = 'primary', p.phone, null)),
IF(p.ptype = 'secondary', p.phone, null))
FROM customer JOIN (blah blah)
WHERE customer_id = 1
GROUP BY c.name, c.address1
如果它不起作用,您可能需要在最后两个字段上放置一个聚合函数,例如:MAX(IF(p.ptype ...