私はという名前のテーブルを持っています:candidate_info
3つの列がありid_user
、id_type
そしてvalue
:
- id_type =1=>フルネーム
- id_type =2=>メール
- id_type =3=>郵送先住所
- id_type =4=>電話番号
ユーザー情報を保存するには:
以下の2つのクエリを検討します。これは、行から列に結合されます。
オリジナルのフォーム:
Id User | Id Type | Value
1 | 1 | John
1 | 2 | john@g.com
1 | 3 | Ho Chi Minh
1 | 4 | 123
2 | 1 | Ana
2 | 2 | ana@g.com
2 | 3 | New York
2 | 4 | 456
新規へ:
Id User | Fullname | Email | Mailing_Address | Phone Number
1 | John | john@g.com | Ho Chi Minh | 123
2 | Ana | ana@g.com | New York | 456
1.最初のクエリ:
select
c1.id_user,
c1.value as fullname,
c2.value as email,
c3.value as mailing_address,
c4.value as phone_number
from
candidate_info c1
left join
candidate_info c2 ON c1.id_user = c2.id_user
left join
candidate_info c3 ON c1.id_user = c3.id_user
left join
candidate_info c4 ON c1.id_user = c4.id_user
where
c1.id_type = 1
and c2.id_type = 2
and c3.id_type = 3
and c4.id_type = 4;
2.2番目のクエリ
select
c.id_user,
MAX(IF(c.id_type = 1, c.value, NULL)) as fullname,
MAX(IF(c.id_type = 2, c.value, NULL)) as email,
MAX(IF(c.id_type = 3, c.value, NULL)) as mailing_address,
MAX(IF(c.id_type = 4, c.value, NULL)) as phone_number
from
candidate_info c
where
c.id_type in (1, 2, 3, 4)
group by c.id_user
どちらが良いですか?
編集:意味をなすように、に変更id_entry_field
します。id_type
join
left join