MYSQL比较来自相同列的值

时间:2013-05-22 11:43:40

标签: mysql

好的,我试着查看遍布stackoverflow,我找到的最接近的解决方案是: mysql AND clause on same column multiple times

但我不能使用语句,因为group by,“having”语法不起作用。必须有一个简单的解决方案。

这两个表看起来像这样(简化):

用户:

uid  name
1    person 1
2    person 2
3    person 3

类:

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

我想要同时获得2个值的uid。例如,我想获得作为演员和音乐家的UID。不只是一个值,但必须要求它们两个!

首先我尝试了这个:

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;

这当然不起作用,因为一行不能有2个值。

有人知道解决方案吗?

4 个答案:

答案 0 :(得分:4)

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;

答案 1 :(得分:4)

您可以多次加入categories表格以获得结果:

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

请参阅SQL Fiddle with Demo

答案 2 :(得分:3)

使用having子句

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

答案 3 :(得分:0)

如果你真的不想使用having,你可以试试这个:

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

但使用HAVING;)

确实没有错