简体   繁体   English

MYSQL - 在多个条件下左加入 - 媒体、标签和标签链接

[英]MYSQL - Left Join on multiple conditions - Medias & Tags & Tag Links

I couldn't find anything that matches my issues.我找不到与我的问题相符的任何内容。

I'm trying to improve my files search query to be able to fetch images by multiple tags (AND and OR).我正在尝试改进我的文件搜索查询,以便能够通过多个标签(AND 和 OR)获取图像。

Fetching images that have one or the other tag is rather easy:获取具有一个或另一个标签的图像相当容易:

SELECT M.*, MTL.tag_id 
FROM medias M 
LEFT JOIN medias_taglinks MTL ON MTL.media_id=M.id 
WHERE ( MTL.tag_id = '1' || MTL.tag_id = '2') 
GROUP BY M.id

But if I want to fetch a image that has both of those tags, I get no results and I'm failing to understand why.但是,如果我想获取具有这两个标签的图像,则不会得到任何结果,而且我无法理解原因。

SELECT M.*, MTL.tag_id 
FROM medias M 
LEFT JOIN medias_taglinks MTL ON MTL.media_id=M.id 
WHERE ( MTL.tag_id = '1' && MTL.tag_id = '2') 
GROUP BY M.id

I'm guessing I need to add my condition to the join but I haven't succeeded yet.我猜我需要将我的条件添加到加入中,但我还没有成功。

SQL FIDDLE HERE: http://sqlfiddle.com/#!9/6e5d6/4 SQL 小提琴在这里: http ://sqlfiddle.com/#!9/6e5d6/4

Checking for an image to have two different tags requires comparing values across rows, which, in turns, suggest aggregation:检查图像是否有两个不同的标签需要跨行比较值,这反过来又建议聚合:

select m.id, m.name
from medias m
inner join medias_taglinks t on t.media_id = m.id
where t.tag_id in (1, 2)
group by m.id, m.name
having min(t.tag_id) <> max(t.tag_id)

The query filters on the two searched tags, aggregates by media, and ensures that both tags are present.查询对两个搜索到的标签进行过滤,按媒体聚合,并确保两个标签都存在。

In your db fiddle, this produces:在您的数据库小提琴中,这会产生:

id | name
-- | ----
1  | Media 1

If you want to handle more than two tags, here is a more generic approach:如果你想处理两个以上的标签,这里有一个更通用的方法:

select m.id, m.name
from medias m
inner join medias_taglinks t on t.media_id = m.id
where t.tag_id in (1, 2, 3, 4)
group by m.id, m.name
having count(*) = 4

This assumes no duplicate (media_id, tag_id) in the tag table;这假设标签表中没有重复的(media_id, tag_id) otherwise, you need having count(distinct t.tag_id) = 4 .否则,您需要having count(distinct t.tag_id) = 4

Side note: the left join seems unnecessary;旁注: left join似乎没有必要; if you want to search medias for tags, you need to bring the tab table anyway.如果要在媒体中搜索标签,则无论如何都需要带上标签表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM