使用两个引用同一个表创建视图

时间:2014-07-17 15:34:33

标签: mysql sql

我有两张桌子

CREATE TABLE `persons` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `first_name` varchar(45) NOT NULL,
 `last_name` varchar(45) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
 CREATE TABLE `marriage` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `place` varchar(45) DEFAULT NULL,
 `spouse1` int(11) NOT NULL,
 `spouse2` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 CONSTRAINT `sp1` FOREIGN KEY (`id`) REFERENCES `persons` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
 CONSTRAINT `sp2` FOREIGN KEY (`id`) REFERENCES `persons` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

现在我想创建一个有婚姻的地方和配偶两个全名的视图。我该怎么做?我试过这样(显然不正确):

CREATE 
  ALGORITHM = UNDEFINED 
  DEFINER = `root`@`localhost` 
  SQL SECURITY DEFINER
 VIEW `mar` AS
select 
    `marriage`.`place` AS `place`,
    `persons`.`first_name` AS `first_name_sp1`,
    `persons`.`first_name` AS `first_name_sp2`
from
    (`persons`
    join `marriage`)
where
    ((`marriage`.`spouse1` = `persons`.`id`)
        and (`marriage`.`spouse2` = `persons`.`id`))

2 个答案:

答案 0 :(得分:4)

您想要的选择需要提及persons两次:

select m.place, p1.first_name as first_name_sp1,
       p2.first_name as first_name_sp2
from marriage m join
     persons p1
     on m.spouse1 = p1.id join
     persons p2
     on m.spouse2 = p2.id;

您只需将create view mar as放在其前面即可将其放入视图中。

并注意使用表别名来区分这两个表。这是需要表别名的情况。但是,它们通常使查询更容易编写和阅读。

答案 1 :(得分:1)

使用别名加入人员两次,我建议用WHERE替换ANSI JOIN联接:

select 
    m.place AS place,
    p1.first_name` AS first_name_sp1,
    p2.first_name AS first_name_sp2
from
    marriage m
     INNER JOIN persons p1
     ON m.spouse1 = p1.id
     INNER JOIN persons p2
     ON m.spouse2 = p2.id