![](/img/trans.png)
[英]MySQL How to select specific records in one table join (1-many) in another table where records have condition on 1 field?
[英]Find all records where one-to-many join table satisfies one condition, but not another condition
我想获取所有具有至少一个Bar类型为“ Apple”的Foos,但在架构中也没有类型为“ Orange”的Bar:
Foo
----
id
Bar
----
id
foo_id
type
如果我的数据是这样的:
Foos
----
| id |
| 1 |
| 2 |
| 3 |
Bars
----
| id | foo_id | type |
| 1 | 1 | Apple |
| 2 | 1 | Orange |
| 3 | 3 | Apple |
该查询将仅返回ID = 3的Foo,因为1具有一个Apple,但也具有一个Orange,并且2没有橙色,但也没有Apple。
另外,我将用Rails标记此帖子,因为首选ActiveRecord解决方案,但不是必需的。
您可以使用sql
SELECT foo_id FROM test.bars GROUP BY foo_id HAVING SUM(IF(type = 'Apple',1,0)) > 0 AND SUM(IF(type = 'Orange',1,0)) = 0 ;
或在ActiveRecord中相同:
bars.group(:foo_id).having('SUM(IF(type = "Apple",1,0)) > ?',0).having('SUM(IF(type = "Orange",1,0)) = ?', 0)
我认为最好使用子查询来执行此操作。 SQL:
Foo.find_by_sql("SELECT f.* FROM foo f WHERE
f.id IN (SELECT foo_id FROM bar x WHERE x.type='Apple') AND
f.id NOT IN (SELECT foo_id FROM bar WHERE x.type='Orange')")
阿雷尔:
Foo.where(id: Bar.select("foo_id").where(type: 'Apple'))
.where.not(id: Bar.select("foo_id").where(type: 'Orange'))
我在自己的模式中测试了这两种方法,因此对于转换到您的域的任何错字,我都表示歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.