We are trying to get filtered custom field data out of the Moodle database via SQL query. Unfortunately it's necessary to join multiple tables to get the data we need, because Moodle keeps its data this way. Also we can't manipulate the data structure. The database looks something like this (simplified):
// table mdl_customfield_field
ID shortname
================
8 language
11 institutions
// table mdl_customfield_data
ID fieldid instanceid value
=============================
1 8 1 2
2 8 2 1
3 11 1 1,2
4 11 2 2,3
5 11 3 1
We tried to get every record that has language 1 AND institution 2 with the following code.
SELECT * FROM mdl_course c
JOIN mdl_customfield_data d ON c.id = d.instanceid
JOIN mdl_customfield_field f ON f.id = d.fieldid
WHERE (f.shortname = 'institutions' AND (d.value LIKE '%,2,%' OR d.value LIKE '2,%'
OR d.value LIKE '%,2' OR d.value = '2'))
AND (f.shortname = 'language' AND d.value = '1')
Using an AND in the last line of the query, the result set does not contain the language data and an OR is showing too many results. How can we just get the course that satisfies both conditions in the result?