Question

I want to filter data based on an array, similar to "in" keyword in a query:

SELECT count(*) as number_of_records, 
       count(CASE WHEN result = 'SUCCESS' THEN 1 END) as successful_builds_no,
       min(CASE WHEN result = 'FAILURE' THEN 0 ELSE 1 END) as is_success,
       min(duration) as best_duration,
       max(build_date) as build_date     
FROM   mdl_selenium_results
WHERE build_date in ('2014-03-13', '2014-03-12')
GROUP BY build_date 

How to achieve that using Moodle DB api??

Was it helpful?

Solution

If you are creating an SQL query to use within Moodle, you could just use the IN keyword, exactly as you have done in the example.

Alternatively, to make it a bit more cross-DB compatible, and to make your queries run a bit faster when there is only one item in the list, you can write:

list($dsql, $dparam) = $DB->get_in_or_equal(array('2014-03-13', '2014-03-12'), SQL_PARAMS_NAMED);

$sql = "SELECT count(*) as number_of_records, 
       count(CASE WHEN result = 'SUCCESS' THEN 1 END) as successful_builds_no,
       min(CASE WHEN result = 'FAILURE' THEN 0 ELSE 1 END) as is_success,
       min(duration) as best_duration,
       max(build_date) as build_date     
FROM   {selenium_results}
WHERE build_date $dsql
GROUP BY build_date";

$result = $DB->get_records_sql($sql, $dparams);

OR, if you just want to get all the matching records from the given table (and then worry about doing the calculations in PHP), you could write:

$result = $DB->get_records_list('selenium_results', 'build_date', array('2014-03-13', '2014-03-12'));

(I've not run any of the code above, so apologies for any typos)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top