开发者

Exclusive query using SQL IN()

开发者 https://www.devze.com 2023-01-26 13:07 出处:网络
This query is pretty self explanatory: $networks = \'6,7,8\'; $query = \"SELECT DISTINCT countryName FROM countries AS Country

This query is pretty self explanatory:

$networks = '6,7,8';

$query = "SELECT DISTINCT countryName 
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
WHERE n.network_id IN (".$networks.")";

However, if I want to select the network number 8, but NOT 6,7, how would I do that?

kind of a IN('8') but NOT I开发者_如何学GoN('6,7')

The use of IN() is a not requirement.

I am after the countries that ONLY have a network of 8. The reason being is that I have 2 levels of cell-phone. Say, the 'scumbag-phone' that works in networks 6 & 7, and the 'Uber-phone' that works in networks 6,7 & 8. I want to get the countries where it is essential that you have an Uber-phone (8 only). At the moment these queries will get 8, but not exclusively. They pay no heed to the fact that there may also be 6,7 in there, deeming the Uber-phone non-essential.


If you do IN('8') then 6,7 will automatically not selected.

You're putting too much thought into this. But still if you want to write it, then do this:

n.network_id IN('8') AND n.network_id NOT IN(6,7)


You might not even need this answer anymore but I ran through some very similiar problem and I solved it by doing something like this:

SELECT DISTINCT countryName 
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
WHERE n.network_id IN ('8') and countryName not in (
    SELECT DISTINCT countryName 
    FROM countries AS Country
    INNER JOIN countries_networks AS n ON Country.id = n.country_id
    WHERE n.network_id IN ('6', '7')
);

With that you are exclusively selecting only the ones in which network_id is '8' and necessarily not '6' and '7'.


$query = "SELECT DISTINCT countryName 
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
WHERE n.network_id in (8) AND not n.network_id  in (6, 7)


There are no stupid questions, only stupid answers...

Here is my attempt:

'$query = "SELECT DISTINCT countryName FROM countries AS Country INNER JOIN countries_networks AS n ON Country.id = n.country_id WHERE n.network_id IN( "8") AND n.network_id NOT IN( "6,7") ";`

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号