在第二个查询中加入2个查询或使用on的结果

时间:2018-11-26 09:36:30

标签: sql sql-server

我有一个查询,可以根据搜索条件提供搜索产品的类别

这意味着查询将提供在给定搜索条件下将找到其产品的所有类别。

第一个查询的值需要像第二个一样使用

    WITH
      sub_categories AS (
        select categories.left, categories.right
        from categories 
        inner join ...
        inner join ...


        where ....
      ),
      main_categories AS (
       SELECT * 
        FROM categories
        WHERE lft < 9 AND rgt > 10 
      )
SELECT *
  FROM main_categories 
  UNION 
  SELECT *
  FROM sub_categories 

在我要替换的main_categories

WHERE left < 9 AND right > 10 

使用sub_categories中的值,我的意思是9应该替换为sub_categories.left或类似的东西

1 个答案:

答案 0 :(得分:1)

您可以在下面尝试

 WITH
      sub_categories AS (
        select categories.left, categories.right
        from categories 
        inner join ...
        inner join ...


        where ....
      ),
      main_categories AS (
       SELECT * 
        FROM categories inner join sub_categories on categories.id=sub_categories.id
        WHERE lft < sub_categories.left AND rgt > sub_categories.right
      )
SELECT *
  FROM main_categories 
  UNION 
  SELECT *
  FROM sub_categories