1

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

但是我不能使用语句,并且由于 group by,“拥有”语法将不起作用。必须有一个简单的解决方案。

2 个表如下所示(简化):

用户:

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

4 回答 4

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;
于 2013-05-22T11:45:30.933 回答
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

于 2013-05-22T11:47:09.603 回答
3

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
于 2013-05-22T11:45:24.197 回答
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;)

于 2013-05-22T11:48:09.123 回答