【问题标题】:SQL Filter by List of idsSQL 按 id 列表过滤
【发布时间】:2020-02-19 11:26:05
【问题描述】:

我有三张桌子

1-rests
2-amenity_rest
3-amenities
rests
id      name
1       rest1
2       rest2
3       rest3

amenities
id     name
1      amenity1
2      amenity2
3      amenity3

amenity_rest
rest_id         amenity_id
1                  1
1                  3
2                  2
3                  1

我想发送 [1,3] 等便利设施清单

它应该返回id=1的其余部分

如果我发送数组 [1,2,3] 它应该不返回任何结果

这样的查询看起来如何?

【问题讨论】:

  • MySQL 不支持数组,所以你的问题不清楚。
  • 我的意思是数组是设施 ID 列表
  • @ShenoudaShehata 为什么 [1,3] 的输出应该是 [1] 而不是 [1,3]
  • 我不明白,我猜你在这里将数组发送到设法进行查询的控制器,对吧?如果您发送 [1,3],它不应该返回 id=2 的行吗?
  • @Tarun 因为便利设施的 id [1,3] 与休息 1 相关

标签: php mysql sql laravel


【解决方案1】:

您可以将查询构造为:

select ar.rest_id
from amenity_rest ar
where ar.amenity_id in (1, 2, 3)
group by ar.rest_id
having count(*) = 3;  -- "3" = size of list

【讨论】:

    【解决方案2】:

    你的控制器应该有这样的功能:

    function retrieveData(Request $request){
        $data = Amenities_rest::whereIn('amenity_id', $request->amenities)
                                ->groupBy('rest_id')
                                ->havingRaw('COUNT (*) = ' . count($request->amenities))
                                ->get();
        return $data
    }
    

    应该这样做。希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-20
      • 2021-10-20
      • 1970-01-01
      • 2013-01-08
      • 2021-12-31
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多