简体   繁体   中英

SQL SELECT everything except parameter

Let's say you have a query where you select something based on a paramater like this :

$parameters = [$country];
$query = 'SELECT g.* FROM game g ' .
            'INNER JOIN game_country gc ON g.id = gc.gameId ' .
            'INNER JOIN countries c ON c.id = gc.countryId ' .
            'WHERE c.name = ? ';
$stmt = $this->_db->query($query, $parameters);

So how this works is you select the countries that you want to be used.

My goals is to select the countries that will be excluded from the select.

So what I've tried is this in the WHERE clausule

'WHERE c.name <> ? ';

This works great as long as you select 1 country as soon as I select more it doesn't work. Does anyone know how I can fix this?

Any help is realy appreciated!

Many thanks in advance

try with NOT IN :

'WHERE c.name NOT IN ( ? ) ';

And the params:

$stmt = $this->_db->query($query, implode(',',$parameters));

You try like like

// it is reset the index
$param_array = array_values($parameters);
$qMarks = str_repeat('?,', count($param_array) - 1) . '?';

$query = 'SELECT g.* FROM game g ' .
            'INNER JOIN game_country gc ON g.id = gc.gameId ' .
            'INNER JOIN countries c ON c.id = gc.countryId ' .
            'WHERE c.name NOT IN ($qMarks) ';
$stmt = $this->_db->query($query, $parameters);

Note: $parameters should be array.

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