mysql查询选择多个连接 - >不同

时间:2013-12-26 06:23:26

标签: mysql distinct

我有一张包含客户,电话号码和传真号码的表格。 客户可以拥有多个电话号码和传真号码。 当我用

选择客户数据时
SELECT customer.FirstName, customer.Id, phone.Phonenumber, fax.Faxnumber
FROM customer
LEFT JOIN phone ON customer.Id = phone.CustomerId
LEFT JOIN fax ON customer.Id = fax.CustomerId
WHERE customer.Id =7
LIMIT 0 , 30

由于此客户有2个电话号码和2个传真号码,我收到了4行

FirstName   Id  Phonenumber     Faxnumber
Wim         7   090-123-1248    093-123-1234
Wim         7   090-123-1248    093-123-1235
Wim         7   090-123-1249    093-123-1234
Wim         7   090-123-1249    093-123-1235

有没有办法只获取一次电话号码和传真号码? 像这样

FirstName   Id  Phonenumber     Faxnumber
Wim         7   090-123-1248    093-123-1234
Wim         7   090-123-1249    093-123-1235

我一直在阅读DISTINCT,但没有找到解决方案。

3 个答案:

答案 0 :(得分:2)

使用GROUP_CONCAT尝试distinct

SELECT 
  customer.FirstName, 
  customer.Id, 
  GROUP_CONCAT(distinct phone.Phonenumber), 
  GROUP_CONCAT(distinct fax.Faxnumber)
FROM customer
LEFT JOIN phone ON customer.Id = phone.CustomerId
LEFT JOIN fax ON customer.Id = fax.CustomerId
WHERE customer.Id = 7
GROUP BY customer.id
LIMIT 0 , 30

它会给你一些类似的东西:

FirstName   Id  Phonenumber                  Faxnumber
Wim         7   090-123-1248,090-123-1249    093-123-1234,093-123-1235

然后,您可以轻松地将电话号码和传真号码分解到程序中的数组。

答案 1 :(得分:0)

你可以做到,但它不像GROUP_CONCAT答案那么漂亮。 sqlFiddle

SELECT customer.FirstName, customer.Id, p.Phonenumber, f.Faxnumber
FROM customer
LEFT JOIN (SELECT phoneNumber,
                  customerId,
                  IF (@prevCustomer != customerId,@row:=1,@row:=@row+1)
                  as row,
                  @prevCustomer := customerId
           FROM phone,(SELECT @row:=0,@prevCustomer:=0)r
           ORDER BY customerId)as p
ON customer.Id = p.CustomerId
LEFT JOIN (SELECT faxNumber,
                  customerId,
                  IF (@prevCustomer != customerId,@row:=1,@row:=@row+1)
                  as row,
                  @prevCustomer := customerId
           FROM fax,(SELECT @row:=0,@prevCustomer:=0)r
           ORDER BY customerId)f 
ON customer.Id = f.CustomerId
AND (p.row = f.row OR p.row IS NULL)
WHERE customer.Id = 7
LIMIT 0 , 30

适用于电话号码与传真号码相同或更多的情况。如果您有更多传真号码,则电话号码将不会显示额外的传真号码。所以我建议你使用GROUP_CONCAT答案。它更安全。

答案 2 :(得分:-3)

你可以添加“分组依据”来分组你的手机行,所以你的SQL就像这样

SELECT customer.FirstName, customer.Id, phone.Phonenumber, fax.Faxnumber
FROM customer
LEFT JOIN phone ON customer.Id = phone.CustomerId
LEFT JOIN fax ON customer.Id = fax.CustomerId
WHERE customer.Id =7
GROUP BY phone.Phonenumber,fax.Faxnumber
LIMIT 0 , 30