Raf A.
Raf A.

Reputation: 126

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?

Upvotes: 1

Views: 10594

Answers (4)

Jens
Jens

Reputation: 2075

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 ;)

Upvotes: 1

Taryn
Taryn

Reputation: 247630

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

Upvotes: 4

user330315
user330315

Reputation:

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;

Upvotes: 4

juergen d
juergen d

Reputation: 204746

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

Upvotes: 3

Related Questions