mysql从具有确切子行数的联接表中选择查询

sy5wg1nm  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(365)

我有两张table如下。
权限访问实体

peID      |   petID
-------------------
1         |   1
2         |   4
3         |   1
4         |   2
5         |   4
6         |   4
-------------------

权限访问权限组

pegID     |   peID     |  gID
-----------------------------
1         |   5        |  1
2         |   5        |  2
3         |   5        |  3
4         |   6        |  2
5         |   6        |  3
-----------------------------

现在我有一个 getOne 条令查询如下-

select pae.peID from PermissionAccessEntities pae 
left join PermissionAccessEntityGroups paeg1 on pae.peID = paeg1.peID 
left join PermissionAccessEntityGroups paeg2 on pae.peID = paeg2.peID 
where petID = 4 and paeg1.gID = 2 and paeg2.gID = 3;

它回来了 5 & 6 . 但是我想得到匹配行的确切数目。在这种情况下 6 .
是否有任何方法可以使用join来获取与上面相同的结果集?。
非常感谢你的帮助。

e4yzc0pl

e4yzc0pl1#

SELECT pae.peID FROM PermissionAccessEntities pae 
INNER JOIN PermissionAccessEntityGroups paeg1 ON  pae.peID=paeg1.peID
WHERE pae.petID = 4 AND paeg1.peID NOT IN (SELECT DISTINCT peID FROM 
PermissionAccessEntityGroups WHERE gID NOT IN (2,3));
wwtsj6pe

wwtsj6pe2#

您可以通过首先查找与(2,3)匹配的条目,然后查看其中是否有与其他值之一匹配的条目来获得所需的结果。任何没有的( paeg2.peID IS NULL )完全匹配:

SELECT DISTINCT(pae.peID)
FROM PermissionAccessEntities pae 
JOIN PermissionAccessEntityGroups paeg1 ON paeg1.peID = pae.peID AND paeg1.gID IN (2,3)
LEFT JOIN PermissionAccessEntityGroups paeg2 ON paeg2.peID = pae.peID AND paeg2.gID NOT IN (2,3)
WHERE pae.petID = 4 AND paeg2.peID IS NULL

在dbfiddle上演示

smdnsysy

smdnsysy3#

Where 这种情况对你没有帮助。因为,您需要考虑所有行的计数以进行进一步筛选。你需要使用 Group By 使用条件筛选 Having 条款。
我们还可以简化查询,只使用一个 PermissionAccessEntityGroups table。 Count() 函数用于计算组中的行数。我们也可以使用 Sum( conditional statements ) 计算符合条件的行数。条件语句将为匹配行返回1,为不匹配行返回0。
请尝试以下查询:

SELECT pae.peID 
FROM PermissionAccessEntities AS pae 
LEFT JOIN PermissionAccessEntityGroups AS paeg 
  ON pae.peID = paeg.peID 
WHERE pae.petID = 4
GROUP BY pae.peID
HAVING COUNT(*) = SUM(paeg.gID IN (2,3))

db小提琴演示

现在,记住这一点 Count(NULL) = 0 ; 然而 COUNT(0) = COUNT(1) = 1 . 所以,另一种使用 Count() 功能仅为:

SELECT pae.peID 
FROM PermissionAccessEntities AS pae 
LEFT JOIN PermissionAccessEntityGroups AS paeg 
  ON pae.peID = paeg.peID 
WHERE pae.petID = 4
GROUP BY pae.peID
HAVING COUNT(*) = COUNT(CASE WHEN paeg.gID IN (2,3) THEN 1 END)

小提琴演示2

相关问题