简体   繁体   English

SQL灵活查询结果

[英]SQL flexible query results

Im still quite new to the SQL side of things. 我对SQL方面还很陌生。 I have been trying to suss out how to you an in criteria but have it decide if the query is just equal to 1 result or multiple. 我一直在尝试向您介绍条件,但是让它确定查询是否等于1个结果或多个结果。 What I have is below. 我所拥有的如下。

I could be doing this all wrong but thought i'll ask. 我可能做错了所有,但以为我会问。

 SELECT employee_name
      , transaction_id
      , department
      , transaction_date
      , transaction_day
   FROM employee_transactions
  WHERE transaction_date 
BETWEEN '2018-08-20 07:14:35.000' 
    AND '2019-02-05 08:29:56.000'
    AND CASE WHEN '$variable' = 'All' 
             THEN inc_day IN (
                 SELECT DISTINCT transaction_day 
                   FROM employee_transactions
           ) ELSE inc_day in ('$variable')
             END

what i mean is in the column transaction day there are entries of Monday, Tuesday, Wednesday ect however all is not in there. 我的意思是在柱交易日中,有星期一,星期二,星期三等条目,但是都不在那里。 So on the form before if they select all it pulls from all days rather than just one however if they pull from monday then just show monda 因此,在表单上,​​如果他们选择了全天的所有数据,而不只是一整天,但是如果他们选择了周一的数据,则只显示monda

You should be writing your query like following. 您应该像下面这样编写查询。

SELECT employee_name, 
        transaction_id, 
        department, 
        transaction_date, 
        transaction_day

  FROM employee_transactions
  WHERE transaction_date 
  BETWEEN '2018-08-20 07:14:35.000' 
  AND '2019-02-05 08:29:56.000'
  AND ( '$variable' = 'All' OR inc_day = '$variable')

Above query will return all the records when $variable = 'ALL' otherwise only matching record. 以上查询将在$ variable ='ALL'时返回所有记录,否则仅匹配记录。

Assuming that '$variable' will get replace before the query gets executed. 假设在查询执行之前“ $ variable”将被替换。

You can try like this 你可以这样尝试

if($variable == "All")
{ 
   $query = "SELECT employee_name, transaction_id , department , transaction_date , 
   transaction_day
   WHERE transaction_date BETWEEN '2018-08-20 07:14:35.000' AND '2019-02-05 08:29:56.000'
   GROUP BY transaction_date"
}
else
{
   $query = "SELECT employee_name, transaction_id , department , transaction_date , transaction_day
   FROM employee_transactions
   WHERE transaction_date BETWEEN '2018-08-20 07:14:35.000'  AND '2019-02-05 08:29:56.000'
   AND inc_day in ($variable)"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM