mySql按

时间:2016-03-24 20:51:38

标签: mysql

我一直在靠墙砸墙几天试图找出如何使这项工作。

我有一张桌子"客户"以下

CustID  |   CatName
----------------
1        ModelX

1        ModelY

2        ModelX

3        ModelY

然后是另一张桌子"价格"

ModelName  |  Price
--------------------
ModelX        $1000

ModelY        $500

ModelZ        $200

所需的输出将是

ID  | ModelName |  Price
-------------------------
1      ModelX      $1000

1      ModelY      $500 

1      ModelZ      $200

2      ModelX      $1000

2      ModelY      $500

2      ModelZ      $200

3      ModelX      $1000

3      ModelY      $500

3      ModelZ      $200 

我不清楚如何为每个ID获取每个不匹配的CatName。当我进行外连接时,我会得到丢失的记录,但它只会列出一次,如果匹配至少一个CatName,那么它将不会匹配其中没有匹配的其他CatNames。 ,即

CustID  |   CatName  | Price
----------------------------
1           ModelX     $1000

1           ModelY     $500

2           ModelX     $1000

2           ModelY     $500

3           ModelY     $500

(null)      ModelZ     $200

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您显示的结果应该是CutsID和客户与价格之间的笛卡尔积的区别

  select distinct * 
  from ( select  a.custID as custID, b.modelName, b.price  
          from customers as a, price b ) as mytable
  order by custID;

答案 1 :(得分:0)

将每个价格行加入Custoners中的每个不同ID:

select CustID, CatName, Price
from Prices, (select distinct CustID from Customers) c