【问题标题】:Sql query reading more than one rowsql查询读取多行
【发布时间】:2018-06-06 16:13:44
【问题描述】:

我有一张表,其中存储了每天可用的工具。 这是结构

    |   Tool_ID  |     Date         |   Available   |
---------------------------------------
    |    1       |     20180501     |       1         |
    |    1       |     20180502     |       3         |
    |    1       |     20180503     |       1         |
    |    2       |     20180501     |       1         |
    |    2       |     20180502     |       0         |
    |    2       |     20180503     |       2         |

我们可以假设 toolID 1 是锤子,toolID 2 是铁砧。

我想不费吹灰之力地找出这 3 天是否有可用的工具。 例如,至少有 1 个 toolID=1,锤子可用,同时 5 月 2 日没有铁砧可用。

有没有办法在 SQL 查询中找到它?

【问题讨论】:

标签: mysql sql database


【解决方案1】:

嗯,想到 group bymin()

select tool_id,
       (case when count(*) < 3 then 0
             else min(available)
        end) as min_available_for_all_three_days
from tools t
where date >= '20180501' and date < '20180504'
group by tool_id;

这假设如果缺少一行,则该工具不可用。

【讨论】:

    【解决方案2】:
    select tool_id from
    (
    select tool_id,date,sum(available) as tot_avl_on_day from tools
    group by tool_id,date
    )t
    where tot_avl_on_day=0;
    

    这将检查任意天数以及工具是否在所有天都可用。

    【讨论】:

      【解决方案3】:
      select IF(
          (select count(*) 
           from tools 
           where (date >= '20180501' and date <= '20180503')
               and tool_id = 1 and available > 0
          ) = 3,
          (
              (select count(*) 
               from tools 
               where (date >= '20180501' and date <= '20180503')
                   and tool_id = 2 and available > 0
              ) = 3,
              "Yes all the tools are available",
              "Tool 2 not available"
          ),
      
          "Tool 1 not available"
      );
      

      【讨论】:

        【解决方案4】:

        这会将可用天数与日期范围内的天数相匹配。您可能必须将您的日期值转换为日期类型。

        SELECT
            `Tool_ID`,
            SUM(IF(`Available` > 0,1,0)) as `daysAvailable`
        FROM `Tools`
        WHERE `Sate` BETWEEN '2018-05-01' AND '2018-05-03'
            AND `daysAvailable` = DATEDIFF('2018-05-03','2018-05-01');
        

        【讨论】:

          猜你喜欢
          • 2018-06-18
          • 1970-01-01
          • 1970-01-01
          • 2013-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-05
          相关资源
          最近更新 更多