MySQL-如果用户ID出现在多行中,则从表中选择用户ID


MySQL - Select userid from table if it appears in multiple rows

不幸的是,我不太确定如何用词表达,所以可能在其他地方得到了答案,但我找不到。无论如何,这似乎是一个简单的问题。我可以想出冗长的方法来做到这一点,但考虑到我对SQL还很陌生,我不想知道最有效的方法是什么。

下面是我所拥有的数据示例:两个连接的表。

-------------------------------------------------------
userid    attributeid    attributename    attributetype
-------------------------------------------------------
1         1              Python           Skill
1         5              C++              Skill
1         2              London           Location
2         1              Python           Skill
2         3              Warsaw           Location
3         4              MySQL            Skill
3         2              London           Location

问题:基本上,我想最终得到拥有技能("Python"或"MySQL")和位置"London"的用户的ID。

因此,在本例中,我将得到用户ID 1和3。

有什么想法吗?如果以前解决过这个问题,请告诉我其他地方。

看起来您有一个标准设置,其中包含用户属性表。尝试此查询:

SELECT userid
FROM users
WHERE EXISTS
    (SELECT 1
     FROM attributes
     WHERE users.userid = attributes.userid
       AND attributetype = 'Skill'
       AND attributename IN ('Python',
                             'MySQL'))
  AND EXISTS
    (SELECT 1
     FROM attributes
     WHERE users.userid = attributes.userid
       AND attributetype = 'Location'
       AND attributename = 'London')

以下是一个基本查询,它应该会为您提供所需的结果:

SELECT `userid`
FROM `table_name_goes_here`
WHERE (`attributename` IN ('Python', 'MySQL') AND `attributetype` = 'Skill')
AND (`attributename` IN ('London') AND `attributetype` = 'Location')
GROUP BY `userid`

您可以使用自加入,一个用于attributetype是技能,另一个用于attributetype是位置,然后调整attributename 的条件

select t.*
from t
join t t1 on(t.userid= t1.userid)
where t.attributetype ='Skill'
and t1.attributetype ='Location'
  and t.attributename  in('Python','MySQL')
 and t1.attributename  = 'London'

演示

SELECT userId
FROM table
WHERE attributename = 'London'
    AND attributename in ('MySQL', 'Python')

这可能会对您有所帮助:

select userid from tag where attributetype='Skill' AND 
attributename IN ('Python','MySQL') AND userid IN
(select distinct(userid) from tag where 
  (attributetype='Location' AND attributename='London'))