麻烦在MySQL中创建视图

时间:2013-09-17 11:13:39

标签: mysql sql database view

我正在尝试创建一个视图来显示表格中的信息。我遇到的麻烦是加入两个表然后分别显示数据。

我有两个表:一个是tbl_videos,另一个是tbl_categories_videostbl_videos有两个类别字段,这两个字段都来自tbl_categories_videoscategory_idtbl_videos中正确显示,但是当我创建视图时,我无法正确显示类别名称。

我最接近它的工作方式是category_1category_2在视图中显示相同的值,但应该是不同的。

我一直盯着屏幕看了太长时间,所以我可能会错过一些简单的东西。

无论如何,这是我对视图的SQL:

CREATE VIEW `VIDEOS_view` AS 
SELECT `tbl_videos`.`videos_id` AS `videos_id`,
       `tbl_videos`.`date` AS `date`,
       `tbl_videos`.`author` AS `author`,
       `tbl_videos`.`photo_credit` AS `photo_credit`,
       `tbl_categories_videos`.`category_videos_name` AS `category_1`,
       `tbl_categories_videos`.`category_videos_name` AS `category_2`,
       `tbl_videos`.`thumb` AS `thumb`,
       `tbl_videos`.`image_1` AS `image_1`,
       `tbl_videos`.`video_embed` AS `video_embed`,
       `tbl_videos`.`title` AS `title`,
       `tbl_videos`.`sub_title` AS `sub_title`,
       `tbl_videos`.`section_1` AS `section_1`,
       `tbl_videos`.`section_2` AS `section_2`,
       `tbl_videos`.`embed` AS `embed`
FROM ((`tbl_videos` join `tbl_categories_videos` on (
    (`tbl_videos`.`category_id_1` AND 
      `tbl_videos`.`category_id_2` =`tbl_categories_videos`.`category_videos_id`
    ))))

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

CREATE VIEW `VIDEOS_view` AS 
SELECT `tbl_videos`.`videos_id` AS `videos_id`,
`tbl_videos`.`date` AS `date`,
`tbl_videos`.`author` AS `author`,
`tbl_videos`.`photo_credit` AS `photo_credit`,
(select category_videos_name from tbl_categories_videos where category_videos_id = tbl_videos.category_id_1) AS `category_1`,
(select category_videos_name from tbl_categories_videos where category_videos_id = tbl_videos.category_id_2) AS `category_2`,
`tbl_videos`.`thumb` AS `thumb`,
`tbl_videos`.`image_1` AS `image_1`,
`tbl_videos`.`video_embed` AS `video_embed`,
`tbl_videos`.`title` AS `title`,
`tbl_videos`.`sub_title` AS `sub_title`,
`tbl_videos`.`section_1` AS `section_1`,
`tbl_videos`.`section_2` AS `section_2`,
`tbl_videos`.`embed` AS `embed`
FROM `tbl_videos`

使用此查询,您只需通过现有外键tbl_videos.category_id_1tbl_videos.category_id_2使用嵌套的select语句从第二个表中选择类别的名称。因此,对于每个id,它会查找匹配tbl_category_videos的{​​{1}}。

你的查询的问题是你不能在两个不同的列上加入一个表,因为然后mysql不知道它必须加入哪个category_videos_name导致没有加入id s是不同的。