MySQL / PHP检索项目在第二个表中出现的次数

时间:2012-12-16 21:45:28

标签: php mysql codeigniter

第一次来这里......

我在MySQL中遇到了一个问题:

我有一些表'产品',其中包含product_id,itemcode,label,price等.... 还有第二个表'库存',其中包含第一个字段的一些公共字段。字段'itemcode'最容易比较两个表。

产品从每个'itemcode'项目只有一个外观。但是,库存有多次。

我需要做什么: 我需要输出“产品”中每个“商品代码”出现在“广告资源”中的次数。最好的方法是什么?

例如

products
  itemcode
  AA2244G
  AB2245G
  AC2246G
  AD2247G
  AE2248G

inventory
  itemcode
  AA2244G
  AA2244G
  AB2245G
  AC2246G
  AC2246G
  AC2246G
  AE2248G

Output
 AA2244G 2x
 AB2245G 1x
 AC2246G 3x
 AD2247G 0x
 AE2248G 1x

1 个答案:

答案 0 :(得分:0)

SELECT  a.itemcode, CONCAT(COUNT(b.itemcode), 'x') totalCount
FROM    products a 
        LEFT JOIN inventory b
            ON a.itemcode = b.itemcode
GROUP BY a.itemcode