[英]Multiple Insert and Select Statements From Multiple Tables into one Query?
I have these all running as a cron job PHP and it is working, but seems to go slow and I don't think it's very efficient.我将这些都作为 Cron 作业 PHP 运行并且它正在运行,但似乎运行缓慢,而且我认为它的效率不高。 There are 5 queries and the basic idea behind it is to find new SKU's in the table and insert them into a MasterSKU table.有 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);
I am then going in one by one in the PHP script and using mysqli_query
to perform each individual query.然后我将一一进入 PHP 脚本并使用mysqli_query
来执行每个单独的查询。
Is it possible to group all of these, even though they are all coming FROM
different tables?是否有可能将所有的这些,即使他们都来FROM
不同的表? Or is there a better, more optimized way to do this?或者有没有更好、更优化的方法来做到这一点?
The answer is no and yes.答案是否定的。
It is no because if you want to extract data from multiple tables that are not related to each other, you need to use separate queries.不是,因为如果要从多个互不相关的表中提取数据,则需要使用单独的查询。
It is yes because in sql you can use union to append the results of multiple queries together - provided they have the same number of fields.是的,因为在 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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.