[英]JOIN 2 tables with where condition, but show first row from table2
I have 2 tables.我有2张桌子。 One is movie table, where all movie data is stored and another one is relation table, where I can see which movie is attached to which category.一个是电影表,其中存储了所有电影数据,另一个是关系表,我可以在其中查看哪个电影附加到哪个类别。 If I want to show movies from category 6 I join them like this:如果我想放映第 6 类电影,我会像这样加入它们:
SELECT t1.title, t2.category FROM movies t1
JOIN movie_categories t2 ON t1.movieid = t2.movieid
WHERE t2.category = 6
And it works just fine.它工作得很好。 However, movie SEF url are generated based on the first row from table2 (actually it should connect to table3, a category table, where i will find sef alias name, but for now I dont need that, I just want to know how to get first category).但是,电影 SEF url 是基于 table2 的第一行生成的(实际上它应该连接到 table3,一个类别表,在那里我会找到 sef 别名,但现在我不需要那个,我只想知道如何获取第一类)。 So lets say, movie have 3 categories, which will be looking like this:可以说,电影有 3 个类别,如下所示:
Table 2 [relations table]
id movieid category
1 1 3
2 1 6
3 1 2
Table 1 [movie table]
movieid
1
2
The query I showed before returns results like this:我之前展示的查询返回这样的结果:
title category
bla1 6
bla2 6
However to create sef url, I need to get the first category id from relations table which is 3 in this case.但是,要创建 sef url,我需要从关系表中获取第一个类别 id,在这种情况下为 3。
I'd like to know how to construct query to achieve the result I described.我想知道如何构造查询来实现我描述的结果。
ASSUMPTION: by MIN you mean the lowest ID in movie_Categories and then display it's category value.假设:MIN 是指movie_Categories 中最低的ID,然后显示它的类别值。
. .
drop table movie;
drop table movie_categories;
create table movie (movieid int, Title varchar(10));
create table movie_categories (Id int, movieID int, category int);
insert into movie values (1, 'The');
insert into movie values (2, 'End');
insert into movie_categories values (1,1,3);
insert into movie_categories values (2,1,6);
insert into movie_categories values (3,1,2);
--To aid in understanding you may want to select * and see why this works and remove the where clause.
--Basically the two joins to Movie_Categories is once for the LOWEST ID and once again to get the limiting category.
SELECT M.Title, MC1.Category
FROM Movie M
INNER JOIN (SELECT min(ID) ID, MovieID
from movie_categories mc
GROUP BY MovieID) L
on L.MovieID = M.MovieID
INNER JOIN Movie_Categories MC1
on L.MovieID = MC1.MovieID
INNER JOIN Movie_Categories MC2
on l.movieid = mc2.movieid
and L.ID = MC1.ID
where mc2.category = 6
Results in:结果是:
title category
The 3
Note: the 2nd title isn't listed because there are no records in movie_category which match a category of 6.注意:第二个标题没有列出,因为在 movie_category 中没有匹配类别 6 的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.