SQL未知数量的外来列作为标题列?

时间:2018-06-16 09:12:52

标签: php sql

我有2个表,一个用于草稿项目,另一个用于存储有关这些项目的元信息,例如“item”和“item_meta”

CREATE TABLE `item` (
  `item_id` int(10) NOT NULL,
  `item_title` varchar(150) NOT NULL,
  `item_status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `item_meta` (
  `meta_id` int(10) NOT NULL,
  `meta_item_id` int(10) NOT NULL,
  `meta_key` varchar(30) NOT NULL,
  `meta_value` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在“item_meta”中,字段“meta_item_id”引用“item.item_id”,因此我可以存储关于每个项目的无限元信息。我可以生成一个sql结果,其中包含有关项目的每个存储的元信息,并生成一个值为“meta_key”的表作为标题,并将“meta_value”的值作为其值吗?

例如,我存储名为“page”的项目并创建元信息

item_id item_title item_status
------------------------------
1       page       1

meta_item_id meta_key  meta_value
--------------------------------
1            viewable  1
1            groupable 1
1            editable  0
...

我不知道项目将获得多少元信息,我想要一个像

这样的结果
item_id item_title item_status viewable groupable editable ... all other meta keys
--------------------------------------------------------------
1       page    1           1        1         0        ... all other meta values

这是否仅适用于sql,或者我需要在通过php查询后将其存档吗?

迎接

2 个答案:

答案 0 :(得分:1)

enter image description here动态SQL查询:

    create table item
(
  item_id  int,
  item_title  varchar(100),
  item_status int,
    );

  insert into item values(1,'page',1);
  create table item_meta
(
  meta_item_id  int,
  meta_key  varchar(100),
  meta_value int,
    );

    insert into item_meta values(1,'viewable',1);
    insert into item_meta values(1,'groupable',1);
    insert into item_meta values(1,'editable',0);

declare @col varchar(1000)
declare @sql varchar(2000)

select @col = COALESCE(@col + ', ','')+ (meta_key)
from (select distinct meta_key as meta_key from item_meta) K;
set @sql='select item_id,item_title,item_status,' +@col+ '
from
(select item_id,item_title,item_status,meta_value,meta_key from item item
inner join
item_meta meta
on item.item_id=meta.meta_item_id)piv
pivot(max(meta_value)for meta_key in (' +@col+' )
) AS pvt
ORDER BY item_id'
exec (@sql)

答案 1 :(得分:-1)

    I don't know about PHP. But it is possible in sql using cross tab query or by pivot:

    create table item
(
  item_id  int,
  item_title  varchar(100),
  item_status int,
    );

  insert into item values(1,'page',1);
  create table item_meta
(
  meta_item_id  int,
  meta_key  varchar(100),
  meta_value int,
    );

    insert into item_meta values(1,'viewable',1);
    insert into item_meta values(1,'groupable',1);
    insert into item_meta values(1,'editable',0);


select
distinct
item_id,
item_title,
item_status,
min(case when meta_key='viewable' then meta_value end) as viewable,
min(case when meta_key='groupable' then meta_value end) as groupable,
min(case when meta_key='editable' then meta_value end) as editable
from item item
inner join
item_meta meta
on item.item_id=meta.meta_item_id
group by
item_id,
item_title,
item_status