Is it possible to have a wildcard in a column name specified in the WHERE clause? I want to select something but only if a bunch of columns match a certain value (1 in this case). For example:
SELECT COUNT(id) FROM records WHERE *_check = 1
I have a bunch of columns that have _check as the suffix and it would be really nice to use something similar to the above code (which doesn't work).
You could query the information_schema to get the columns in one query
SELECT column_name FROM information_schema.columns
WHERE table_schema = 'foo'
AND table_name = 'bar'
AND column_name LIKE '%_check'
and build your query from the result (pseudo code)
query = "SELECT COUNT(id) FROM records WHERE ";
foreach columName in columnNames
query = query + " " + column_name + " = 1 OR "
next
query = TrimLastOr(query);
But I wouldn't recommend that because mysql information_schema query have a poor performance since they read from disk for every query.
Better: Use a view that returns
SELECT id FROM records WHERE col1_check=1 or col2_check=2 ...
so you can use it in your logic on multiple places, and only have to update the view if you add another _check
column.
No.
If you want to do something like this, you need the equivalent of dynamic SQL.