SQL-组合查询

时间:2019-02-11 10:25:32

标签: php mysql sql

我有两个查询可以完全按照我的意愿进行,但是,我想尝试将它们组合起来。

查询1:

SELECT DISTINCT categories.id FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 
    WHERE 
        categories.is_sub_cat='1' AND 
        categories.is_paused!='1' AND 
        products.nexus='1'

查询2:

SELECT DISTINCT categories.top_cat FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 
    WHERE 
        categories.top_cat!='0' AND 
        categories.is_paused!='1' AND 
        products.nexus='1'

是否可以将它们组合成1个查询,还是应该在执行完两个查询后将结果数组组合到PHP中?

5 个答案:

答案 0 :(得分:3)

您可以使用UNION合并两个查询

SELECT DISTINCT categories.id FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 
    WHERE 
        categories.is_sub_cat='1' AND 
        categories.is_paused!='1' AND 
        products.nexus='1'
UNION 

SELECT DISTINCT categories.top_cat FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 
    WHERE 
        categories.top_cat!='0' AND 
        categories.is_paused!='1' AND 
        products.nexus='1'

答案 1 :(得分:0)

您可以在以下情况下使用大小写

SELECT case when (categories.is_sub_cat='1' AND  categories.is_paused!='1' AND 
        products.nexus='1') then categories.id
        else categories.top_cat end  as id
    FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 

答案 2 :(得分:0)

您可以将查询合并为

SELECT DISTINCT categories.id, categories.top_cat FROM categories 
    INNER JOIN product_categories 
        ON product_categories.category_id=categories.id 
    INNER JOIN products 
        ON product_categories.product_id=products.id 
    WHERE 
        ( categories.is_sub_cat='1' OR categories.top_cat!='0' ) AND 
        categories.is_paused!='1' AND 
        products.nexus='1'

或者,如果列UNION ALLcategories.id具有相同的数据类型,或者可以强制转换为相同的数据类型,则可以使用categories.top_cat

答案 3 :(得分:0)

是的,UNION似乎是一个合法的选择。对于您的情况,这无关紧要,因为您是从同一张表中进行选择,但是作为一个侧面说明,您应该知道,在使用UNION时,您的表中的列数必须相等(也就是说,它们不同)。

答案 4 :(得分:0)

您可以使用WHERE子句中的条件来做到这一点:

SELECT DISTINCT c.id
FROM categories c INNER JOIN
     product_categories pc
     ON pc.category_id = c.id INNER JOIN
     products p
     ON pc.product_id = p.id 
WHERE p.nexus = 1 AND
      c.is_paused <> 1 AND
      (c.is_sub_cat = 1 OR
       c.top_cat <> 0 
      );

注意:

  • 表别名使查询更易于编写和阅读。
  • 假设列是数字,请不要将值与字符串进行比较。尝试避免类型转换问题。