MySQL:如果所有值都存在,则返回true

时间:2014-06-04 12:27:26

标签: php mysql sql

如何使用一个查询来检查我的数据库中是否填满了所有日期,我的数组包含应填写的所有日期和我的数据库。我在考虑使用IN但是无法使用它,到目前为止,我的查询看起来像这样

SELECT `User` . * , `Department`.`name`, if(Hour.date IN('2014-05-05', '2014-05-05', ...), 1, 0) AS all_days_filled
FROM `kadry`.`users` AS `User`
    LEFT OUTER JOIN `kadry`.`departments` AS `Department` ON ( `Department`.`id` = `User`.`assigned` )
    LEFT OUTER JOIN `kadry`.`hours` AS `Hour` ON ( `Hour`.`subordinate_id` = `User`.`id` )
WHERE `User`.`assigned`
IN (
    '001004012', '116', '113', '114', '004001002'
)
AND `role` != 'superior'
AND `Department`.`active` = '1'
AND `User`.`active` = '1'
AND ((date( discharge ) > '2014-05-01')
OR (
    discharge IS NULL
   )
)
GROUP BY `User`.`id`
ORDER BY `Department`.`name` ASC , `User`.`l_name` ASC 

3 个答案:

答案 0 :(得分:1)

您可以尝试GROUP_CONCAT功能。它将默认返回逗号连接的日期。如果需要其他分隔符,可以将其指定为选项。您也可以将DISTINCTORDER BY放入GROUP_CONCAT

请参阅mysql doc http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

SELECT `User` . * , `Department`.`name`, 
CASE
WHEN GROUP_CONCAT(Hour.date ORDER BY HOUR.date) = '2014-05-01, 2014-05-02, ...' THEN 1 
ELSE 0
END AS all_days_filled
FROM `kadry`.`users` AS `User`
    LEFT OUTER JOIN `kadry`.`departments` AS `Department` ON ( `Department`.`id` = `User`.`assigned` )
    LEFT OUTER JOIN `kadry`.`hours` AS `Hour` ON ( `Hour`.`subordinate_id` = `User`.`id` )
WHERE `User`.`assigned`
IN (
    '001004012', '116', '113', '114', '004001002'
)
AND `role` != 'superior'
AND `Department`.`active` = '1'
AND `User`.`active` = '1'
AND ((date( discharge ) > '2014-05-01')
OR (
    discharge IS NULL
   )
)
GROUP BY `User`.`id`
ORDER BY `Department`.`name` ASC , `User`.`l_name` ASC 

答案 1 :(得分:1)

您可以使用SUM来累计给定范围内的天数。将总和与范围内的实际天数进行比较。如果它们不相等,那么你就错过了几天。这是相关代码:

IF(SUM(IF(Hour.date BETWEEN '2014-05-01' AND '2014-05-31', 1, 0)) = 31, 1, 0) AS all_filled

答案 2 :(得分:0)

此查询解决了我的问题

SELECT `User`. * , `Department`.`name` , IF( SUM( IF( Hour.date
IN (
    "2014-05-05", "2014-05-06", "2014-05-07", "2014-05-08", "2014-05-09", "2014-05-12", "2014-05-13", "2014-05-14", "2014-05-15", "2014-05-16", "2014-05-19", "2014-05-20", "2014-05-21", "2014-05-22", "2014-05-23", "2014-05-26", "2014-05-27", "2014-05-28", "2014-05-29", "2014-05-30"
), 1, 0 ) ) >=20, 1, 0 ) AS all_filled
FROM `kadry`.`users` AS `User`
     LEFT OUTER JOIN `kadry`.`departments` AS `Department` ON ( `Department`.`id` = `User`.`assigned` )
     LEFT OUTER JOIN `kadry`.`hours` AS `Hour` ON ( `Hour`.`subordinate_id` = `User`.`id`
AND date( `Hour`.`date` )
BETWEEN '2014-05-01'
AND '2014-05-31' )
    WHERE `User`.`assigned`
    IN (
        '001004012', '116', '113', '114', '004001002'
        )
    AND `role` != 'superior'
    AND `Department`.`active` = '1'
    AND `User`.`active` = '1'
    AND (
        (
            date( discharge ) > '2014-05-01'
        )
    OR (
    discharge IS NULL
    )
)
GROUP BY `User`.`id`
ORDER BY `Department`.`name` ASC , `User`.`l_name` ASC