将第一个查询的结果用作第二个查询的条件

时间:2020-02-18 12:19:27

标签: mysql sql

我有以下SQL表,您也可以在var obj = {id = 1, name = 'product1'}; var clonedObject = {...obj}; here中找到该表:

SQL fiddle

我目前使用以下查询:

CREATE TABLE Products (
    Supplier TEXT,
    Product TEXT,
    Quantity VARCHAR(255)
);

INSERT INTO Products
(Supplier, Product, Quantity)
VALUES 

("Supplier_01", "Product A", "500"),
("Supplier_05", "Product A", "300"),
("Supplier_09", "Product A", "250"),

("Supplier_05", "Product B", "900"),
("Supplier_06", "Product B", "270"),
("Supplier_02", "Product B", "850"),
("Supplier_05", "Product B", "950"),
("Supplier_10", "Product B", "630");

但是,现在我想将以上查询的部分结果用作第二个查询的SELECT Supplier, Product, Quantity FROM Products WHERE Product = "Product B"; 标准。
基本上,我希望将WHERE存在的所有Suppliers用于Product B的{​​{1}}标准。
像这样的东西:

WHERE

最终所需的结果应如下所示:

Product A

我需要在代码中进行哪些更改才能使其正常工作?

2 个答案:

答案 0 :(得分:0)

您快到了:

SELECT Supplier, Product, Quantity
FROM Products
WHERE Supplier IN
   (SELECT Supplier
    FROM Products
    WHERE Product = "Product B")
GROUP BY 1,2
ORDER BY 2,1;

答案 1 :(得分:0)

您可以在此处使用以下脚本。 INNER JOIN可用于过滤查询。

SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
  FROM (SELECT A.SUPPLIER, A.PRODUCT, A.QUANTITY
         FROM PRODUCTS A) A
   INNER JOIN (SELECT DISTINCT SUPPLIER
                 FROM PRODUCTS
                WHERE PRODUCT = "Product B") B
      ON B.SUPPLIER = A.SUPPLIER

sqlfiddle demo