简体   繁体   中英

MySQL Query To Select Rows Where Column Has Both of 2 Values in Entire Result Set

I have single a table that contains IP data from a number of websites I run in which I use a column SiteCode to identify what data originates from what website like this:

ID    SiteCode    IP            Page
--    --------    --            ----
1     BHS         192.168.1.1   index.php
2     ED          192.168.4.4   index.php
3     BHS         192.168.1.1   index.php
4     ED          192.168.1.1   index.php

What I am trying to do, is figure out how I can select only those IP numbers which have SiteCodes in rows for both (not either) BHS and ED in the result set:

SELECT * FROM `ip-tracking` WHERE `IP`='192.168.1.1' ?????

I hope I have been clear.

Many thanks in advance.

Using condtional aggregation while grouping on each IP address you can check to make sure that an IP is associated with both types of site code:

SELECT IP
FROM yourTable
GROUP BY IP
HAVING SUM(CASE WHEN SiteCode = 'BHS' THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN SiteCode = 'ED'  THEN 1 ELSE 0 END) > 0

If BHS and ED are the only two site codes which ever appear in the table, then the HAVING clause can be simplified to:

HAVING COUNT(DISTINCT SiteCode) = 2

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