我有两个sql查询,我需要将它们组合成一个查询以提高效率,但不确定如何做到这一点。基本上我需要查询我的供应商,然后为每个供应商检查以查看列表中是否有多个匹配的记录基于"供应商ID",如果是,那么我需要返回供应商名称和ID。以下是我的两个问题:
查询1:
SELECT s.name, s.id
FROM Supplier s
查询2:
SELECT l.asin,
l.id,
COUNT(*) c
FROM Listing l
LEFT JOIN Product p
ON p.id = l.product_id
LEFT JOIN Supplier s
ON p.supplier_id = s.id
WHERE (l.matchValidated IS NULL OR l.matchValidated = 0)
AND s.id = SUPPLIER_ID_GOES_HERE
GROUP BY l.asin HAVING c > 1);
答案 0 :(得分:0)
您已在第二个查询中加入了供应商,因此您只需将供应商名称和ID添加到SELECT
和GROUP BY
。
SELECT l.asin,
l.id,
s.name AS supplier_name,
s.id AS supplier_id,
COUNT(*) c
FROM Listing l
LEFT JOIN Product p
ON p.id = l.product_id
LEFT JOIN Supplier s
ON p.supplier_id = s.id
WHERE (l.matchValidated IS NULL OR l.matchValidated = 0)
GROUP BY l.asin, l.id, s.name, s.id
HAVING c > 1;