mysql - 连接和多重和条件

标签 mysql sql symfony1 doctrine-1.2

我有用户表

ID     NAME
1      John
2      Mike
3      Jack

以及包含属性和用户 ID 的表

USER   ATTRIBUTE
1      1
1      2
2      4

我需要选择具有属性 1 AND 2 的所有用户(因此,在此示例中为用户 #1 John)。属性可以多于两个。

我试过了

SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user 
WHERE a.attribute = 1 AND a.attribute = 2

但当然它不起作用..

最佳答案

您需要结合使用 IN()GROUP BY ... HAVING 来实现此目的。如果您只需要用户 ID,也无需加入。所以类似:

SELECT user, COUNT(attribute) AS attribute_count
FROM attributes
WHERE attribute IN(...) /* include your set of attributes here */
GROUP BY user
HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */

如果您需要用户 ID 和名称,您只需将从上述查询派生的记录集作为过滤器加入到用户表中即可:

SELECT user.id, user.name
FROM user
INNER JOIN
  (
    SELECT user, COUNT(attribute) AS attribute_count
    FROM attributes
    WHERE attribute IN(...) /* include your set of attributes here */
    GROUP BY user
    HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */
  ) AS filter
  ON user.id = filter.user

关于mysql - 连接和多重和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26004866/

相关文章:

mysql - Laravel 按关系属性订购数据

mysql - 根据事件日期显示 mysql 表上的特定字段

sql - Sql Azure 数据库中区分大小写的列名称

sql - Spring JPA : No converter data from DB in to DTO

css - 如何在管理生成器中使用自定义 CSS 文件(对于 sfGuardUser)?

php - 如何选择 ORM

python - Django 查询日期时间

mysql - SQL查询在内部连接到右表后从左表中选择不同的行

mysql - 如何启动 MySQL,以便对查询/索引的性能进行基准测试?

php - Symfony - 更新唯一列 - 验证问题