【问题标题】:mysql equivalent of IN() clause doing logical AND's insteadmysql 等效于 IN() 子句执行逻辑与代替
【发布时间】:2012-08-15 20:14:07
【问题描述】:

假设我有一个表在两个表之间建立连接......就像这样:

id_product | id_category
-----------------
11 | 22
11 | 33
12 | 22
12 | 33

我想根据搜索到的类别 ID 列表获取 id_products (distinct)。

如果我使用 IN() 子句,则 id_categories 列表使用逻辑 OR。

如何进行 SELECT 查询以对提交的 id_categ 列表进行逻辑与?

示例:我想要属于类别 22 的所有 id_products AND 33(可能还有 5 个以上的类别 ID)

我找到了这个答案: Using MySQL IN clause as all inclusive (AND instead of OR) ...但是查询混合了多个表...我只想在单个表上进行查询,即联结表。

【问题讨论】:

标签: mysql


【解决方案1】:

阅读您的链接,我认为它会像

select id_product 
from yourTable
where id_category in (--your List goes Here)
group by id_product 
having count(distinct id_category) = NumberOfElementsOfYourList

您应该使用 = if 只想获取该 id_category,但不获取其他 id_category。 如果没有,请使用 >=

【讨论】:

  • 我在您的 HAVING 子句中将 COUNT(distinct id_product) 更改为 COUNT(distinct id_category)...COUNT(distinct id_product) 对于每个 id_product 组将始终为 1。
  • 你今天拯救了我的一天。 :-)
【解决方案2】:
select id_product
from your_table
where id_category in (22, 33)
group by id_product
having count(distinct id_category) = 2

您可以添加一个having 子句来计算找到的id_category。例如,如果您查找 5 个 ID,则必须在 having 子句中更改 5 中的 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2018-11-01
    • 2022-08-15
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多