[英]How to LEFT JOIN table1 ON table2 WHERE table2 row fulfills certain conditions
[英]JOIN 2 tables with where condition, but show first row from table2
我有2張桌子。 一個是電影表,其中存儲了所有電影數據,另一個是關系表,我可以在其中查看哪個電影附加到哪個類別。 如果我想放映第 6 類電影,我會像這樣加入它們:
SELECT t1.title, t2.category FROM movies t1
JOIN movie_categories t2 ON t1.movieid = t2.movieid
WHERE t2.category = 6
它工作得很好。 但是,電影 SEF url 是基於 table2 的第一行生成的(實際上它應該連接到 table3,一個類別表,在那里我會找到 sef 別名,但現在我不需要那個,我只想知道如何獲取第一類)。 可以說,電影有 3 個類別,如下所示:
Table 2 [relations table]
id movieid category
1 1 3
2 1 6
3 1 2
Table 1 [movie table]
movieid
1
2
我之前展示的查詢返回這樣的結果:
title category
bla1 6
bla2 6
但是,要創建 sef url,我需要從關系表中獲取第一個類別 id,在這種情況下為 3。
我想知道如何構造查詢來實現我描述的結果。
假設: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
結果是:
title category
The 3
注意:第二個標題沒有列出,因為在 movie_category 中沒有匹配類別 6 的記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.