0

我有一张名为 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  |            |
+--------------+------------+

我的查询返回两行,其中一为空,但我需要单行。任何人都可以指导我正确的方向来完成它。

谢谢

4

3 回答 3

1

此表必须与另一个store表相关。而且我猜您实际上想显示商店的一些详细信息及其联系方式。

为此,将store_contact两次加入此store表。把这张store_contact桌子想象成两张单独的桌子,一张只保存电话号码,另一张只保存传真号码。我假设store_contact.destination_id是一个外键store

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'
于 2013-06-11T13:26:59.617 回答
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
于 2013-06-11T13:33:27.683 回答
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. 它更标准。

于 2013-06-11T13:17:40.140 回答