2

我有一个人员可用性表:

         +---+---+---+---+---+---+
         | M | T | W | F | S | S |
         +---+---+---+---+---+---+
Olivier  |   |   |   |   | X | X |
         +---+---+---+---+---+---+
Georges  | X |   |   | X |   |   |
         +---+---+---+---+---+---+

所以我有三张桌子:

  • 可用性
  • person_availability

我正在做如下查询:

SELECT p.*
FROM person p
JOIN person_availability pa
ON p.id=pa.person_id
JOIN availability a
ON a.id=pa.availability_id
WHERE p.id = ?
AND a.day in (?)

带有动态参数。示例:param1=1和 param2=(1,4,5)

问题是此查询返回在这些可用性之一中可用的人员行。如何改变拥有所有这些可用性的人(1,4,5)

4

2 回答 2

0

我建议这样做:

将您的 param2 放入具有以下结构的临时表中:

DECLARE @Days TABLE 
(
    Day INT
)

(将日期插入表中)

那么您的查询可以是:

SELECT P.*
FROM person P
CROSS JOIN @Days D
-- Only include people where all the days are in their available days
WHERE D.Day IN
    (
        SELECT A.Day
        FROM availability A
        JOIN person_availability PA ON A.availability_id = PA.availability_id
        JOIN person P1 ON P1.person_id = PA.person_id
        WHERE P1.person_id = P.person_id
    )
AND P.person_id = PARAM1
于 2013-10-21T15:05:31.990 回答
0

您执行 aGROUP BY p.id然后将其与HAVING COUNT(a.day)等于您的IN (?). 这样,您可以确保获得 IN 子句中每个人的值,如果您提供 3 个值并且 COUNT 返回 3,则您知道该人具有所有可用性。

像这样:

SELECT p.*
FROM person p
JOIN person_availability pa ON p.id = pa.person_id
JOIN availability a ON a.id = pa.availability_id
WHERE p.id = 1 AND a.day IN (1,2,3)
GROUP BY p.id
HAVING COUNT(a.day) = 3;

sqlfiddle demo

于 2013-10-21T15:06:16.277 回答