次のようなテーブルで、1対Nの関係がある場合products
:
products
+----+------+
| id | name |
+----+------+
| 1 | foo |
| 2 | bar |
+----+------+
そしてoptions
このようなテーブル:
options
+----+------------+--------+--------+
| id | product_id | option | active |
+----+------------+--------+--------+
| 10 | 1 | size | true |
| 11 | 1 | color | false |
| 12 | 2 | size | true |
| 13 | 2 | color | true |
+----+------------+--------+--------+
どうすればproducts
彼のすべてのオプションを備えたを入手できますactive = true
か?商品に。が付いたオプションが少なくとも1つある場合、active = false
その商品をクエリで取得したくないことに注意してください。
この場合の望ましい結果は製品2になります。
サブクエリを使用してbool_and
、すべての値が次の場合にのみtrueを返すPostgresのブール集計を使用してすべてアクティブなオプションテーブルからproduct_idsを取得できます。true
select *
from products
where id in (select product_id
from options
group by product_id
having bool_and(active));
オンラインの例:http://rextester.com/ILPX66228
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加