如何从左表中获取所有行乘以右表

时间:2014-03-11 08:58:29

标签: mysql sql

我有以下两个表:

  Table: ProductList
  Product;
   Product a
   Procuct b 
   Product c
   ...
   Product Z

Table: SalesTable
Agent, Product, Qty
 ZXY, Product A, 200
 ABC, Product A, 100
 ABC, Product B, 200

我想要一张包含所有产品列表*代理商列表的表格。 所以,对于instnace:

   Agent, Product, Qty
   ZXY, Product A, 200
   ZXY, Product B,  -
   ZXY, Product C,  - 
   ....
   ABC, Product A, 100
   ABC, Product B, 200
   ABC, Product C, -
   ABC, Product D, - 

使用:

SELECT * 
  FROM ProductTable
       LEFT JOIN AgentTable 
            ON ProductTable.Product = SalesTable.Product
显然,

不起作用。

3 个答案:

答案 0 :(得分:0)

您可以尝试这样

Select Distinct B.Agent,A.Product,C.Qty

from

Product A

Cross JOIN SalesTable B 

Left join SalesTable C on C.Product=A.Product and C.Agent=B.AGENT

Sql Fiddle Demo

答案 1 :(得分:0)

SELECT t1.Agent, t1.Product, COALESCE(s.Qty, '-') AS Qty
  FROM (
        SELECT a.Agent, p.Product
          FROM (SELECT DISTINCT Agent FROM SalesTable) a
               CROSS JOIN
               (SELECT DISTINCT Product FROM ProductList) p
        ) t1 LEFT JOIN SalesTable s
                  ON (t1.Product = s.Product 
                      AND t1.Agent = s.Agent)

答案 2 :(得分:-2)

尝试此查询

SELECT ST.*
FROM ProductList PL
JOIN SalesTable ST ON PL.Product = ST.Product
ORDER BY ST.Agent, ST.Product

已删除分组依据,因为订单是必需的而不是分组

SQLFiddle - http://www.sqlfiddle.com/#!2/30335/18