简体   繁体   中英

MYSQL compare values from same columns

Okay I tried to look all over stackoverflow, and the closest solution I found is this: mysql AND clause on same column multiple times

But I can't use statements and "having" syntax won't work because of group by. There MUST be a simple solution to this.

The 2 tables looks like this (simplified):

users:

uid  name
1    person 1
2    person 2
3    person 3

categories:

uid  value
1    actor
1    musician
2    actor
3    dancer
4    musician
4    dancer

I want to get the uid of those that are 2 values at the same time. For example, I want to get the UID that is an actor AND a musician. Not just one value, but both of them must be required!

First I tried this:

SELECT users.uid, users.name 
FROM 
users
LEFT OUTER JOIN categories ON users.uid = categories.uid
WHERE (categories.value = 'actor' AND categories.value = 'musician')
GROUP BY u.uid;

This of course does not work since one row can't have 2 values.

Does anyone know a solution?

SELECT users.uid, users.name 
FROM users
  LEFT JOIN categories ON users.uid = categories.uid
WHERE categories.value in ('actor', 'musician')
GROUP BY u.uid, users.name
having count(distinct categories.value) = 2;

You can JOIN to the categories table multiple times to get the result:

SELECT users.uid, users.name 
FROM users
INNER JOIN categories c1
  ON users.uid = c1.uid
INNER JOIN categories c2
  ON users.uid = c2.uid
WHERE c1.value = 'actor' 
  AND c2.value = 'musician';

See SQL Fiddle with Demo

Use a having clause

SELECT u.uid, u.name 
FROM users u
LEFT OUTER JOIN categories c ON u.uid = c.uid
WHERE c.value = 'actor' OR c.value = 'musician'
GROUP BY u.uid
having count(distinct c.value) > 1

If you really do not want to use having you could try this:

SELECT uid, name 
FROM users
WHERE 
uid IN (SELECT uid FROM categories WHERE value='actor')
AND uid IN (SELECT uid FROM categories WHERE value='musician')

But there is really nothing wrong with using HAVING ;)

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