如何从mysql中的两行中获取单行

时间:2013-06-11 13:16:15

标签: mysql select

我有一个名为store_contact的表

+--------------------------+--------------------------+--------------+----------------+
| store_contact_numbers_id | phone_number_description | phone_number | destination_id |
+--------------------------+--------------------------+--------------+----------------+
|                      121 | Fax                      | 5555555555   |            287 |
|                      123 | Main                     | 4444444444   |            287 |
+--------------------------+--------------------------+--------------+----------------+

,上表所需的输出如下所示:

+--------------+------------+
| Phone_Number | Fax_Number |
+--------------+------------+
|  4444444444  | 5555555555 |
+--------------+------------+

我尝试过这样的事情:

select if(phone_number_description='MAIN',phone_number,'') as Phone_Number,
if(phone_number_description='FAX',phone_number,'')  as Fax_Number
 from store_contact where destination_id=287

但我的上述查询返回的内容如下:

+--------------+------------+
| Phone_Number | Fax_Number |
+--------------+------------+
|              | 5555555555 |
| 44444444444  |            |
+--------------+------------+

我的查询返回两行一行,但我需要单行。 请任何人指导我正确的方向来完成它。

由于

3 个答案:

答案 0 :(得分:1)

SELECT (SELECT IF(phone_number_description = 'MAIN', phone_number, '') 
        FROM   store_contact 
        WHERE  destination_id = 287) AS Phone_Number, 
       (SELECT IF(phone_number_description = 'FAX', phone_number, '') 
        FROM   store_contact 
        WHERE  destination_id = 287) AS Fax_Number 

使用IF而不是使用CASE块。它更标准。

答案 1 :(得分:1)

此表必须与另一个store表相关。我猜你实际上想要显示商店的一些细节及其联系方式。

为此,请将store_contact两次加入此store表。可以把store_contact表看作是两个独立的表,一个只保存电话号码,另一个只保留传真号码。我假设store_contact.destination_idstore的外键。

SELECT
    store.name, -- and other fields as required
    phone.phone_number AS phone_number,
    fax.phone_number AS fax_number
FROM store
JOIN store_contact AS phone
    ON (phone.destination_id = store.id AND phone.phone_number_description = 'Main')
JOIN store_contact AS fax
    ON (fax.destination_id = store.id AND fax.phone_number_description = 'Fax')
WHERE destination_id = 287

对于您要求的非常具体的结果,这就足够了:

SELECT
    phone.phone_number AS phone_number,
    fax.phone_number AS fax_number
FROM store_contact AS phone
JOIN store_contact AS fax USING (destination_id)
WHERE destination_id = 287
AND phone.phone_number_description = 'Main'
AND fax.phone_number_description = 'Fax'

答案 2 :(得分:1)

你可以使用这样的查询:

SELECT
  MAX(CASE WHEN phone_number_description='Main' THEN Phone_Number END) Phone_Number,
  MAX(CASE WHEN phone_number_description='Fax' THEN Phone_Number END) Fax_Number
FROM
  store_concat
WHERE
  destination_id=287
GROUP BY
  destination_id