0

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

我有两张桌子:一张是tbl_videos,另一张是tbl_categories_videostbl_videos有两个类别字段,都取自tbl_categories_videos. category_ids 正确显示,但是tbl_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`
    ))))

任何帮助将非常感激。

4

1 回答 1

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_1使用此查询,您只需通过现有外键和tbl_videos.category_id_2嵌套选择语句从第二个表中选择类别名称。因此,对于每个id它都会查找tbl_category_videos匹配的category_videos_name.

您的查询的问题是您不能在两个不同的列上加入一个表,因为 mysql 不知道它必须加入哪个列,如果s 不同id,则导致不加入。id

于 2013-09-17T11:22:58.417 回答