简体   繁体   English

凡是确切不多多少少mysql

[英]Where count is exact not more or less mysql

I have one_to_many relationship where i have 3 tables images , items and image_items .. every image may have one or many items, i wanna make a query where i pass the item/items id/ids and get a specific image (exactly one image) based on the count of items inside this image ... 我有一个one_to_many关系,其中我有3个表imagesitemsimage_items ..每个图像可能有一个或多个项目,我想查询一个我在其中传递项目/项目ID / ID并获取特定图像(恰好是一个图像)的查询根据此图片中的项目计数...

Here is what i have tried so far but it has a problem, it gives me images with that count or more, i'm not sure if this logic or structure is valid in the first place: 这是到目前为止我尝试过的操作,但是有一个问题,它给我的图像计数或更多,我不确定此逻辑或结构是否首先有效:

SELECT `image_items`.`image_id`
FROM `image_items`
WHERE `image_items`.`item_id` IN(1, 2)
GROUP BY `image_items`.`image_id`
HAVING count(image_items.image_id) = 2 

在此处输入图片说明

Here is the fiddle 这是小提琴

Lets say image (1) has items (1,2,3), image (2) has items (1,3) and image (3) has items (1,2) .. lets say i want the image that has exactly (1,2) .. with my query even with distinct it gives me images (1,3) when i want only image (3). 可以说图像(1)具有项(1,2,3),图像(2)具有项(1,3),图像(3)具有项(1,2)..可以说我想要的图像正好具有(1,2)..即使我的查询与众不同,当我只需要图像(3)时,它也会给我图像(1,3)。

Remove the WHERE clause and add in the HAVING clause a condition : 删除WHERE子句,并在HAVING子句中添加一个条件:

SELECT image_id
FROM image_items
GROUP BY image_id
HAVING 
  COUNT(DISTINCT item_id) = 2 
  AND
  SUM(item_id NOT IN (1, 2)) = 0

See the demo . 参见演示
Result: 结果:

| image_id |
| -------- |
| 4        |

Forpas's solution is a good solution. Forpas的解决方案是一个很好的解决方案。 A slightly simpler having clause is: 稍微简单的having条款是:

SELECT image_id
FROM image_items
GROUP BY image_id
HAVING GROUP_CONCAT(item_id ORDER BY item_id) = '1,2';

If you are constructing this query in an application, this is simpler because you only need to pass in one value, the string '1,2' . 如果要在应用程序中构造此查询,则这会更简单,因为您只需要传入一个值,即字符串'1,2'

I hope you need to use DISTINCT in the HAVING clause as HAVING COUNT(DISTINCT image_id ) = 2 to get the exact count. 我希望您需要在HAVING子句中使用DISTINCT ,因为HAVING COUNT(DISTINCT image_id ) = 2才能获得准确的计数。

SELECT `image_id`
FROM `image_items`
WHERE `item_id` IN (1, 2)
GROUP BY `image_id`
HAVING COUNT(DISTINCT `image_id`) = 2 

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

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