从多个表中多个插入和选择语句到一个查询?

时间:2017-01-11 15:07:15

标签: php mysql

我将这些全部作为cron作业运行PHP并且它正在运行,但似乎进展缓慢,我不认为它非常有效。有5个查询,其背后的基本思想是在表中找到新的SKU并将它们插入到MasterSKU表中。

INSERT INTO MasterSKU (SKU)
SELECT DISTINCT SKU
FROM   AmazonListings
WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  AmazonListings.SKU = MasterSKU.SKU);

INSERT INTO MasterSKU (SKU)
SELECT DISTINCT SKU
FROM   ShopifyListings
WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  ShopifyListings.SKU = MasterSKU.SKU);

INSERT INTO MasterSKU (SKU)
SELECT DISTINCT SKU
FROM   eBayListings_1
WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  eBayListings_1.SKU = MasterSKU.SKU);

INSERT INTO MasterSKU (SKU)
SELECT DISTINCT SKU
FROM   eBayListings_2
WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  eBayListings_2.SKU = MasterSKU.SKU);

INSERT INTO MasterSKU (SKU)
SELECT DISTINCT SKU
FROM   eBayListings_3
WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  eBayListings_3.SKU = MasterSKU.SKU);

然后我在PHP脚本中逐个进行,并使用mysqli_query执行每个单独的查询。

是否可以对所有这些进行分组,即使它们都来了FROM个不同的表?或者有更好,更优化的方法吗?

1 个答案:

答案 0 :(得分:1)

答案是肯定的,是的。

不是因为如果要从多个彼此不相关的表中提取数据,则需要使用单独的查询。

这是肯定的,因为在sql中你可以使用union将多个查询的结果附加在一起 ​​- 只要它们具有相同数量的字段。

INSERT INTO MasterSKU (SKU)
    (SELECT DISTINCT SKU
     FROM   AmazonListings
     WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  AmazonListings.SKU = MasterSKU.SKU))
     union
     (SELECT DISTINCT SKU
     FROM   ShopifyListings
     WHERE  NOT EXISTS (SELECT SKU
                   FROM   MasterSKU
                   WHERE  ShopifyListings.SKU = MasterSKU.SKU)
     union ...