php - Mysql Where Column A = X and Column B = Y and or Column B = Z

标签 php mysql sql relational-database rdbms

我正在尝试从数据透视表中获取一组值,其中 A 列等于值数组,例如 ID 12 的 attribute_value_id 等于 3 和 9。这可以做到吗?我已经走了这么远...

ID | post_id | attribute_id | attribute_value_id
8      12          1             3
9      12          2            13
10     13          1             3
11     13          2             9
12     16          1             3
13     16          2             9
88     11          1             1
89     11          2             8
90     11          3            18
91     11          4            22

查询...

select * 
from `searching_for_posts` 
where (
    select count(*) 
    from `attributes` 
    inner join `searching_for_attributes`
    on `attributes`.`id` = `searching_for_attributes`.`attribute_id` 
    where `searching_for_attributes`.`searching_for_post_id` = `searching_for_posts`.`id` 
    and (`attribute_value_id` = 3 and `attribute_value_id` = 9)
) >= 1

如果我使用 则我得不到任何值。如果我使用 ,那么我会得到 3 个值,但它应该返回 2。我的 SQL 经验有限。

最佳答案

您可以使用 group byhaving 来做到这一点。你的逻辑很难理解,但它是这样的:

select post_id
from table t
where attribute_value_id in (3, 9)
group by post_id
having count(distinct attribute_id) = 2;

我认为您也想检查 attribute_id,但这似乎不是问题的一部分。

编辑:

如果这些存储在另一个表中:

select a.post_id
from attributes a join
     searching_for_attributes sfa
     on a.attribute_id = sfa.attribute_id and
        a.attribute_value_id = sfa.attribute_value_id
group by a.post_id
having count(*) = (select count(*) from searching_for_attributes);

关于php - Mysql Where Column A = X and Column B = Y and or Column B = Z,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356675/

相关文章:

php - 服务器问题空白页 - Apache、Linux、Joomla

php - Laravel 插入一对多关系

mysql - SQL如何连接两个不同的表列作为结果

MySQL查询按年龄、3个月、6个月、9个月和12个月分组

sql - 关于mysql索引,多列还是一个?

mysql - 如何使用 SQL 查找不交叉的时间集?

php - 为什么这个 SQL 没有插入到数据库中?

php - 新值覆盖以前的值

php - 使用 MySQL 数据重新填充/编辑 HTML 表单输入

mysql - 索引k-d树?