list in mysql with join

时间:2011-08-30 20:06:49

标签: php mysql sql wordpress

如何列出此表中的iduser,其中gender = man且int = woman且age = 19?

Table usermeta
----------------------
id  iduser a        b
12  204    age      19
7   203    age      35
6   200    age      24
3   201    age      34
5   201    gender   male
2   200    gender   female
8   203    gender   male
9   204    gender   male
4   201    int      female
10  204    int      male
11  203    int      female
1   200    int      male

答案应该是:

ID用户所

204

我从另一篇文章中得到了这个......

SELECT a.`iduser` FROM `table` a 
JOIN `table` b ON b.`iduser` = a.`iduser` 
WHERE a.`a`='gender' AND a.`b`='man' AND b.`a`='int' AND b.`b`='woman'

但不过滤年龄字段...

感谢。

3 个答案:

答案 0 :(得分:1)

这是投入混音的另一种选择:

SELECT user_id
  FROM wp_usermeta
  WHERE (meta_key = 'age' AND meta_value = '19')
    OR (meta_key = 'gender' AND meta_value = 'male')
    OR (meta_key = 'int' AND meta_value ='male')
  GROUP BY user_id
  HAVING COUNT(*) = 3

答案 1 :(得分:0)

您似乎需要另一个自我加入,我们将其别名为t3。此外,我正在将别名从a,b更改为t1,t2,因为您的示例完全无法读取。 DISTINCT可能是必要的,也可能不是必需的。

SELECT DISTINCT t1.`iduser`
FROM `table` t1
  JOIN `table` t2 ON t1.`iduser` = t2.`iduser` 
  JOIN `table` t3 ON t1.`iduser` = t3.`iduser` 
WHERE 
  t1.`a` = 'gender'
  AND t1.`b` = 'man'
  AND t2.`a` = 19
  AND t3.`b` = 'woman'

答案 2 :(得分:0)

你可以尝试这样的事情,但我认为它会很慢。

SELECT iduser, GROUP_CONCAT(CONCAT(a,':',b) SEPARATOR ',') as groups 
from TABLE
group by iduser
having LOCATE('gender:man', groups) != 0 and LOCATE('int:woman', groups) != 0 and LOCATE('age:19', groups) != 0

我没有在实际数据上检查这个,所以如果发生任何错误,请在评论中记下它们。

另一种方式:

SELECT t1.iduser from table t1 
INNER JOIN table t2 on t1.iduser=t2.iduser and t1.a='age' and t2.a='gender'
INNER JOIN table t3 on t2.iduser = t3.iduser and t3.a='int'
where t1.b='19' and t2.b='man' and t3.b='woman';