简体   繁体   中英

SQL flexible query results

Im still quite new to the SQL side of things. 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. 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

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.

Assuming that '$variable' will get replace before the query gets executed.

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)"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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