MySQL从2个表中查找唯一的产品ID

时间:2010-12-13 06:38:52

标签: sql mysql

我有3张桌子

Table: Products
                productid (int)
                name (varchar)
                description (text)

Table: Sales
                salesid (int)
                productid (int)

Table: Links
                linkid (int)
                productid (int)

现在,我需要一个查询,可以获得sales表或链接表中存在的product-id总数。

帮助表示赞赏。

由于

3 个答案:

答案 0 :(得分:0)

SELECT COUNT(ProductId) 
FROM Products
WHERE
  ProductId IN
    (SELECT ProductId FROM Sales)
OR
  ProductId IN
    (SELECT ProductId FROM Links)
;

编辑:我假设销售或链接表可能包含不在产品中的ProductIds,回想起来实际上没有任何意义。如果Sales和Links中的ProductId字段是Products表中ProductId的外键,那么您可以这样做:

SELECT COUNT(ProductId) FROM
  (
    (SELECT DISTINCT ProductId From Sales)
    UNION
    (SELECT DISTINCT ProductId From Links)
  ) AS ProductIds
;

答案 1 :(得分:0)

只要数据合适,您就不需要检查产品表

SELECT COUNT(1) 
FROM (SELECT distinct ProductId
      from Sales
     UNION -- instead of union all to ensure that only distinct values are taken
      SELECT distinct ProductId
      from Links) products

答案 2 :(得分:0)

您是在寻找所有产品ID还是仅仅是唯一的?

要查找唯一ID,您可以使用以下内容:

SELECT COUNT(t1.ProductId) 
FROM (SELECT ProductId FROM Sales GROUP BY ProductId HAVING COUNT(*) = 1
UNION
  SELECT ProductId FROM Links GROUP BY ProductId HAVING COUNT(*) = 1) t1