Topic on Project:Support desk

Using 'OR' operator in queries

2
173.217.255.81 (talkcontribs)

Simple questions, hopefully a simple solution.

Basically, 'real' SQL queries allow you to do this:
.WHERE 'foo' = 'pi' OR 'bar' = 'pi'

Doing the same in 'Mediawiki style' isn't quite as apparent, though. It seems to only be known how to use the AND operator, like so:

'foo' => 'pi',
'bar' => 'pi'

...With the above example being equivalent to:

WHERE 'foo' = 'pi' AND 'bar' = 'pi'

In the simpleest of terms: How can I uss the 'OR' operator in a query while staying true to the 'wiki' style? I guess I could use the query() function (As opposed to delete(), select(), update(), write() and so forth), but the rest of my queries are 'wiki' style and I prefer for things to remain uniform.

Thanks, if you happen to have the answer.

Florianschmidtwelzow (talkcontribs)

Conditions in Database access layer's select are always connected with AND (like the documentation to this function say: https://doc.wikimedia.org/mediawiki-core/master/php/html/classDatabaseBase.html#a76f9e6cb7b145a3d9020baebf94b499e

If you want to use OR; you can specify the conditions as a string, like (edited example from Manual:Database_access):

$res = $dbr->select(
	'category',                                   // $table
	array( 'cat_title', 'cat_pages' ),            // $vars (columns of the table)
	'( cat_pages > 0 ) OR ( cat_pages = 1 )',     // $conds combined with OR
	__METHOD__,                                   // $fname = 'Database::select',
	array( 'ORDER BY' => 'cat_title ASC' )        // $options = array()
);

But: Maybe you can consider to remove the OR condition if possible, sometimes it ive a way to get the same result with only one condition or with and connected conditions.

Another way that should work is to use DatabaseBase::makeList(). I haven't tested it, but you can define a new var and use this as a condition string (makeList() returns a string), example:

$conds = array(
   'cat_pages > 0',
   'cat_pages' => 1
);
$res = $dbr->select(
	'category',                                   // $table
	array( 'cat_title', 'cat_pages' ),            // $vars (columns of the table)
	$dbr->makeList( $conds, LIST_OR ),            // $conds combined with OR
	__METHOD__,                                   // $fname = 'Database::select',
	array( 'ORDER BY' => 'cat_title ASC' )        // $options = array()
);
Reply to "Using 'OR' operator in queries"