格式化带有多个联接的RIGHT JOIN查询

时间:2019-03-31 13:07:01

标签: mysql sql

我有有效的SQL查询:

SELECT table1.bike_id 
FROM
    ( 
        SELECT bike_id 
        FROM `bike_filters`
        WHERE (`bike_category_id` in (416,11111)) 
    ) as table1
    RIGHT JOIN (
        SELECT bike_id 
        FROM `bike_filters`
        WHERE (`bike_category_id` in (5555,779)) 
    ) as table2 ON table1.bike_id = table2.bike_id
GROUP BY bike_id

但是我需要添加更多RIGHT JOIN行,也许是5条或更多。如何以正确的方式形成查询?我在同一张表中进行搜索,但是在一个查询中将多条记录结合在一起,以获得适合所有条件的bike_id。

此查询的目的是获取bike_id,该查询具有查询的所有参数-自行车可以具有20个过滤器,但是如果用户按5进行搜索并且自行车与之匹配,则此查询将获得bike_id。

表结构:

| id | bike_id | bike_category_id |
| 1  | 3       | 416              |
| 2  | 3       | 779              |
| 3  | 3       | 344              |
| 4  | 3       | 332              |
| 5  | 4       | 444              |
| 5  | 5       | 555              |

我需要这样的东西,这是不正确的:

SELECT table1.bike_id 
FROM
    ( 
        SELECT bike_id 
        FROM `bike_filters` 
        WHERE (`bike_category_id` IN (416,11111)) 
    ) AS table1
    RIGHT JOIN ( 
        SELECT bike_id 
        FROM `bike_filters` 
        WHERE (`bike_category_id` IN (5555,779)) 
    ) AS table2
    RIGHT JOIN ( 
        SELECT bike_id 
        FROM `bike_filters` 
        WHERE (`bike_category_id` IN (5555,344)) 
    ) AS table3
    RIGHT JOIN ( 
        SELECT bike_id 
        FROM `bike_filters` 
        WHERE (`bike_category_id` IN (5555,332)) 
    ) AS table4
GROUP BY bike_id

1 个答案:

答案 0 :(得分:4)

您可以使用聚合,并将所有条件放在HAVING子句中,如下所示:

SELECT bike_id
FROM bike_filters
GROUP BY bike_id
HAVING
   MAX(bike_category_id in (416,11111)) = 1
   AND MAX(bike_category_id in (5555,779)) = 1

这将返回所有bike_id

  • 具有类别416 11111
  • 的类别为5555779

您可以根据需要扩展HAVING子句。