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  |            |
+--------------+------------+

私のクエリは2行を返しますが、1行は空ですが、1行が必要です。誰でもそれを成し遂げるために正しい方向に私を導いてください。

ありがとう

4

3 に答える 3

1

このテーブルは別のstoreテーブルに関連付けられている必要があります。そして、実際には店舗の詳細とその連絡先の詳細を表示したいと思っていると思います。

これを行うには、このテーブルにstore_contact2 回JOIN します。テーブルを 2 つの別々のテーブルであるかのようにstore考えてください。1 つは電話番号のみを保持し、もう 1 つは FAX 番号のみを保持します。への外部キーであると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'
于 2013-06-11T13:26:59.617 に答える