これは MySQL でタグ付けされているため、柔軟なデータベース テーブルを作成する方法があります。次のような名前と値のペアを含むテーブルを作成できます。
create table YourTable
(
id int,
name varchar(50),
attribute varchar(50),
value varchar(50)
);
insert into yourtable
values(1, 'Scott', 'DOB', '07/01/2012'),
(1, 'Scott', 'Address 1', '2222 Jackson'),
(1, 'Scott', 'Health', 'Good'),
(1, 'Scott', 'Expertise Level', 'High'),
(1, 'Scott', 'Contact Info', '408-555-5555');
これは とも呼ばれますEntity-Attribute-Value
。このタイプの構造を使用することには、長所と短所があります。
このデータをクエリするには、複数の結合を実行するか、データをピボットして列に入れる必要があります。
これは、このタイプの構造 (EAV) の概要を示すDBA.SE に関する質問です。
CASE
次のステートメントで集計関数を使用してデータをクエリできます。
select id,
name,
max(case when attribute = 'DOB' then value end) DOB,
max(case when attribute = 'Address 1' then value end) Address1,
max(case when attribute = 'Health' then value end) Health
from yourtable
group by id, name;
複数の結合を実行する場合、クエリは次のようになります。
select t1.id,
t1.name,
t1.value DOB,
t2.value Address1,
t3.value Health
from yourtable t1
left join yourtable t2
on t1.id = t2.id
and t1.name = t2.name
and t2.attribute='Address 1'
left join yourtable t3
on t1.id = t3.id
and t1.name = t3.name
and t3.attribute='Health'
where t1.attribute = 'DOB';
データ取得のデモで SQL Fiddle を参照してください。