检查表中是否存在id's列表,但属于不同的组


Check if list of id's exists in table but with different group

我有两个表和一个itemId的列表

Variable Item Ids: [2,40,41,50,53]

**parent_table**
*id | title | amount*
1  | Test1 | 2
2  | Test2 | 1

父表设置组合的标题以及它需要多少个itemId,如果groupId not为(NULL), amount将始终为1。

**composition_table**
*id | parentId | itemId | groupId*
1  | 1        | 2      | (NULL)  
2  | 2        | 40     | 1
3  | 2        | 41     | 1
4  | 2        | 50     | 2
5  | 2        | 51     | 2
6  | 2        | 53     | 2

所以我这里的任务是检查itemId列表是否可以与composition_table中的一些关系组合。

itemId的有效组合可以是:[40,51],[40,50]或[41,50]等。itemId的无效组合可以是:[40,41],[50,51]或[40]

组合必须有来自每个组的itemId。无效组合被忽略,没有操作。对于每个组合,parent_table。应该选择Id作为输出。

我希望有一个或多个sql查询的解决方案。我试了很多次,但我还是很难适应群体的特点。

这是我的尝试:

SELECT
  pt.id
FROM
  parent_table pt
WHERE
  pt.amount = 1
  AND EXISTS (
    SELECT
      1
    FROM
      composition_table ct
    WHERE
      ct.parentId = pt.id
      AND ct.itemId IN (2,40,41,50,53)
      AND ct.groupId IN (
        SELECT
          GROUP_CONCAT(DISTINCT(ct.groupId))
        FROM
          composition_table ct
        WHERE
          ct.parentId = pt.id
      )
  )

如您所见,我不知道如何检查组合是否只在组不同时输出。

我希望这是可以理解的,有帮助,提前感谢!

编辑:一个结果的例子,我试图得到

array of parent_table.id

array (
 1, 2, 2
)

在项目id[40,50]和[41,53]中有两种组合,请注意,当项目id在组合中使用时,它不能再次使用。

如果composition_table中存在有效的关系,那么输出将是parent_table的id。

仍然不太确定我是否正确理解NULL逻辑,但这是我作为一个开始提出的;

SELECT parentid, MIN(a) numgroups
FROM (
  SELECT g.parentid, g.groupid, COUNT(ct.itemid) a
  FROM (
    SELECT DISTINCT parentid, COALESCE(groupid, 0) groupid 
    FROM composition_table
  ) g 
  LEFT JOIN composition_table ct
    ON g.parentid = ct.parentid
   AND g.groupid  = COALESCE(ct.groupid, 0)
   AND ct.itemid IN (2, 40, 41, 52, 53)
  GROUP BY g.parentid, g.groupid
) z
GROUP BY parentid

给出结果;

parentid    numgroups
1           1
2           2 

(SQLfiddle)

…这意味着1组在父1中,2组在父2中,与您的示例相匹配。

如果需要包含[1,2,2]的数组,只需在从数据库读取时添加父numgroups次。