如何使用这些关系表进行MySQL查询

时间:2016-05-21 20:35:43

标签: mysql relational-database

我有以下表格

videos

id | title | url


video_to_category

video_id | category_id

我想要一个查询来获取视频表中具有某个category_id的所有视频

5 个答案:

答案 0 :(得分:1)

SELECT * FROM videos v, video_to_category vc
WHERE v.id=vc.video_id AND category_id=YOURID

答案 1 :(得分:1)

您可以使用内部联接

select a.* 
from videos as a 
inner join video_to_category as b on a.id = b.video_id
and b.category_id = 'Your_value';

答案 2 :(得分:1)

SELECT * FROM `videos` AS `v`,`video_to_category` AS `vtc`
WHERE `v`.`id`=`vtc`.`video_id`
AND `vtc`.`category_id`='YOUR CHOICE'

OR

SELECT * FROM `videos` `v` INNER JOIN `video_to_category` `vtc` 
ON `v`.`id`=`vtc`.`video_id`
AND `vtc`.`category_id`='YOUR CHOICE'

Example

答案 3 :(得分:1)

select videos.* from videos 
inner join video_to_category 
on video_to_category.video_id = videos.id 
and video_to_category.category_id = 10

通过分析您的表格,您的列video_to_category似乎只有2列,如果是这种情况,那么您不需要将其保存在不同的列中,您可以在视频表名称中添加新列' category_id& #39;,但如果您在此问题中隐藏了其他一些列,请将其保留。

答案 4 :(得分:1)

 select vi.id, vi.title, vi.url from videos vi left join video_to_category 
 vc on (vi.id = vc.video_id) where vc.category_id = '$category_id'

$ category_id是放置给定变量id的变量。我使用“$”因为我在这里使用php varaiable。

由于