简体   繁体   English

SQL查询基于多对多关系选择

[英]SQL query to select based on many-to-many relationship

This is really a two-part question, but in order not to mix things up, I'll divide into two actual questions. 这确实是一个分为两部分的问题,但是为了不混淆,我将分为两个实际问题。 This one is about creating the correct SQL statement for selecting a row based on values in a many-to-many related table: 这是关于创建正确的SQL语句以根据多对多相关表中的值选择行的方法:

在此处输入图片说明

Now, the question is: what is the absolute simplest way of getting all resources where eg metadata.category = subject AND where that category's corresponding metadata.value ='introduction'? 现在的问题是:获取所有resources最简单的绝对方法是什么,例如metadata.category =主题,而该类别的相应metadata.value ='introduction'?

I'm sure this could be done in a lot of different ways, but I'm a novice in SQL, so please provide the simplest way possible... (If you could describe briefly what the statement means in plain English that would be great too. I have looked at introductions to SQL, but none of those I have found (for beginners) go into these many-to-many selections.) 我敢肯定这可以通过许多不同的方式来完成,但是我是SQL的新手,所以请提供最简单的方法...(如果您可以用简单的英语简短地描述该语句的含义,那将是我也看过SQL的入门知识,但是对于初学者来说,我发现的内容都不多。

The easiest way is to use the EXISTS clause. 最简单的方法是使用EXISTS子句。 I'm more familiar with MSSQL but this should be close 我对MSSQL比较熟悉,但是应该很接近

SELECT *
FROM resources r
WHERE EXISTS (
    SELECT *
    FROM metadata_resources mr
        INNER JOIN metadata m ON (mr.metadata_id = m.id)
    WHERE mr.resource_id = r.id AND m.category = 'subject' AND m.value = 'introduction'
)

Translated into english it's 'return me all records where this subquery returns one or more rows, without returning the data for those rows'. 翻译成英文是“将所有记录返回给我,其中该子查询返回一个或多个行,而不返回这些行的数据”。 This sub query is correlated to the outer query by the predicate mr.resource_id = r.id which uses the outer row as the predicate value. 谓词mr.resource_id = r.id将该子查询与外部查询相关联,该谓词使用外部行作为谓词值。

I'm sure you can google around for more examples of the EXIST statement 我确定您可以在Google周围搜索EXIST语句的更多示例

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

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