Filtering rows in mysql with possibility for more values

user2796914 :

I'm new in PHP and MySQL and i have some problems. For me it is easier to explain with a screenshot

For example here i would want to show all people, who can work with Wordpress, Joomla AND Typo3... In this case it should show only Mrs Mustermann I tried WHERE name='joomla' OR name='wordpress' OR name='typo3', but it shows the people, who can work with any of the three... Sorry for my bad english


EDIT

OP note: providing example data is not hard, doesn't flippin matter how "easy" posting an image is

 nachname    vorname  email                name        id
 ---------   -------  -------------------  ---------- --- 
 Mustermann  Mrs                           joomla     148 
 Mustermann  Mrs                           wordpress  148 
 Mustermann  Mrs                           typo3      148 
 Mustermann  Muster   [email protected]  wordpress  158 
 Mustermann  Muster   [email protected]  typo3      158

SELECT t.*
  FROM ( SELECT 'Mustermann' AS nachname,'Mrs' AS vorname,'' AS email,'joomla' AS NAME,'148' AS id
         UNION ALL SELECT 'Mustermann','Mrs','','wordpress','148'
         UNION ALL SELECT 'Mustermann','Mrs','','typo3','148'
         UNION ALL SELECT 'Mustermann','Muster','[email protected]','wordpress','158'
         UNION ALL SELECT 'Mustermann','Muster','[email protected]','typo3','158'
       ) t
GMB :

A typical solution uses group by to aggregate rows having the same nachname, and then to filter with a having clause:

select nachname
from mytable
where name in ('joomla', 'wordpress', 'typo3')
group by id, nachname
having count(distinct name) = 3

I assumed that id is a unique identifier for nachname, so I added it to the group by clause; feel free to remove it if that's not the case.

This query gives you the nachnames that have worked for all three values in the in list.

It is quite easy to adapt the query to handle more (or less) names, by modifying the in list and the target count.

If there are no duplicate (nachname, name) duplicates in the table, you can use count(*) instead of count(distinct ...), which will be more efficient.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302126&siteId=1