简体   繁体   English

如何将在同一表上执行的两个 SQL 查询合并为一个?

[英]How to combine two SQL queries being performed on the same tables into one?

Below are the 2 queries I need to combine into one, and I like to have rows from the left table even if there is no matching row in the right table.下面是我需要合并为一个的 2 个查询,即使右表中没有匹配的行,我也喜欢从左表中获取行。

                    $sql = "SELECT country.printable_name FROM sku"
                    . "LEFT OUTER JOIN country ON country.numcode=sku.c_code"
                    . "WHERE sku.item_sku='JDJ2020'";

                   $sql= "SELECT hs_code FROM hs_codes"
                   . "INNER JOIN sku ON 
                   sku.base_category=hs_codes.base_category AND 
                   sku.sub_category=hs_codes.sub_category"
                   . "WHERE sku.item_sku = 'JDJ2020'";

After PHP code clearing the queries will look like清除 PHP 代码后,查询将如下所示

SELECT country.printable_name 
FROM sku
LEFT OUTER JOIN country ON country.numcode=sku.c_code
WHERE sku.item_sku='JDJ2020';

SELECT hs_code 
FROM hs_codes
INNER JOIN sku ON sku.base_category=hs_codes.base_category 
              AND sku.sub_category=hs_codes.sub_category
WHERE sku.item_sku = 'JDJ2020';

Their combining may look like他们的组合可能看起来像

SELECT country.printable_name, hs_codes.hs_code
FROM sku
INNER JOIN hs_codes ON sku.base_category=hs_codes.base_category 
                   AND sku.sub_category=hs_codes.sub_category
LEFT OUTER JOIN country ON sku.c_code=country.numcode
WHERE sku.item_sku='JDJ2020';

If there exists a row in the country which matches the row in sku always then replace LEFT OUTER JOIN with INNER JOIN .如果存在一个排country该行匹配sku始终然后更换LEFT OUTER JOININNER JOIN

If there exists more than one matched row in country and/or hs_codes then you'll obtain more than one output row.如果country和/或hs_codes存在多个匹配行,那么您将获得多个输出行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM