如何在mysql中创建我的上下文中的视图/表?

时间:2010-02-03 10:54:19

标签: php mysql

我想在mysql中创建一个视图/表。我现在有两张桌子:

create table teacher(
id int(10) not null auto_increment, 
name varchar(50), 
primary key(id)
);
create table student(
id int(10) not null auto_increment, 
name varchar(50), 
teacher_id int(10), 
primary key(id), 
foreign key(teacher_id) references teacher(id) on delete cascade);

现在,我想在同一列中获取teacher.namestudent.name,并将teacher.teacher_id设为parent_id,将student.id设为id

新表应该是结构:

table(parent_id, id, name);  

编辑:

“姓名”列的值是教师姓名或学生姓名。

示例:

parent_id     id             name
  0            1           teacher1
  1            2           student1
  1            3           student2
  0            4           teacher2
  4            5           student3

怎么做?在此先感谢;)

编辑:有人知道该怎么做吗?知道...

1 个答案:

答案 0 :(得分:2)

我不确定我在同一列中获取teacher.namestudent.name是什么意思。我假设你的意思是你想把它们作为一个字符串加在一起,例如“John Smith,Michael Jones”。

CREATE VIEW teacherstudent AS
SELECT teacher.id AS parent_id, student.id AS child_id, CONCAT(teacher.name,', ',student.name) AS name
FROM teacher, student
WHERE teacher.id = student.teacher_id;

您现在可以执行select * from teacherstudent;