我有一个表格,列出了产品可能具有的所有选项(1个产品可以有许多选项):
产品id选项
现在我需要选择所有3个选项1,2,3的所有产品ID,然后我必须这样做

select products_id
from options
where products_id in
     (select products_id
      from options
      where products_id in
              (select products_id
               from options
               where options_id = 3)
      and options_id = 2)
and options_id = 1

如果我不得不说10个选择的话,这似乎是非常无效的。我想知道有没有办法绕过这一切
编辑:
我按要求提供了一些样本数据:
products_id           options_id
1                     1
1                     2
1                     3
1                     4
1                     5
2                     1
2                     2
2                     3
3                     2
3                     3
3                     9
4                     1
4                     2
4                     8

如果我们使用上面的sql,我们应该只得到产品1,2,它有所有选项1,2,3。其他(3,4)没有所有必需的选项

最佳答案

您应该使用递归函数并在表中保留一个字段“parent_id”以定位所有相关产品

关于mysql - 在这种情况下,有没有办法避免多个嵌套选择?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9885245/

10-11 02:51
查看更多