使用许多表创建视图?

时间:2014-01-29 10:38:25

标签: mysql sql view

我使用此语法从表中创建视图:

CREATE VIEW view_name AS 
    SELECT column_name(s) FROM table_name WHERE condition

我将从许多表中创建一个视图。例如,我有两个表:

  • Person:id,first_name,last_name,Age,City_id
  • 城市:id,city_name,zip_code

我尝试此请求从两个表创建一个视图(first_name,last_name,city_name),但它不起作用:

CREATE VIEW view AS 
    SELECT 
        first_name, 
        last_name, 
        (SELECT city_name FROM City where City_id=id ) 
    FROM Person.

有什么问题?

2 个答案:

答案 0 :(得分:0)

您应该使用联接:

CREATE VIEW person_city AS
    select 
        first_name,
        last_name,
        city_name
     from Person p
     join City c
     on p.city_id = c.city_id

请注意,我已在示例SQL中重命名了该视图。通常不建议使用view等保留字来表示数据库对象名称,但如果必须将其命名为view,则可以始终使用反引号。

答案 1 :(得分:0)

CREATE VIEW person_view AS
    SELECT 
        first_name, last_name
    FROM
        Person
            JOIN
        City ON City.id = Person.City_id