在MYSQL中查询,其中列为表名,另一列为列的外键作为表名

时间:2014-11-17 10:21:29

标签: mysql sql phpmyadmin

img_gallary (id,event_type,event_name,image)

其中event_type是表名,event_name是event_type字段之一(即表名列)。

如何根据事件名称及其来自id的特定事件对事件进行分组?

1 个答案:

答案 0 :(得分:0)

create table img_gallary (
  id int primary key,
  event_type varchar(255),
  event_name varchar(255),
  image varchar(255));
insert into img_gallary values
  (1, 'Music', 'Summer Jazz', 'jazz23.jpg'),
  (2, 'Theatre', 'Hamlet', 'Booth_as_Hamlet.jpg'),
  (3, 'Music', 'City Rock', 'brass_at_cityrock.jpg'),
  (4, 'Music', 'Summer Jazz', 'summerj_miller.jpg');

create table music (
  event_name varchar(255) primary key,
  event_date date);
insert into music values
  ('City Rock', '2014-08-10'),
  ('Summer Jazz', '2014-09-13');

create table theatre (
  event_name varchar(255) primary key,
  event_date date);
insert into theatre values
  ('Hamlet', '2014-07-19');

select *
from img_gallary
natural join (
  select 'Music' as event_type, event_name, event_date
  from music
  union
  select 'Theatre' as event_type, event_name, event_date
  from theatre
) event
order by event_type, event_name;

http://sqlfiddle.com/#!2/5a3ee/1