我需要弄清楚两个表之间的匹配数量。
目前,我正在使用此查询,这会导致找到匹配的次数。
SELECT count(*) FROM products WHERE EXISTS (SELECT 1 FROM inventory WHERE products.products_id = inventory.product_id) AND products.orders_id = 'xxx'
如果有5个产品,其中3个可以在另一个表中找到 - 它返回" 3.
我需要能够知道总共有多少行以及有多少行匹配 - 就像找到了3/5。我该怎么做?
答案 0 :(得分:7)
如果产品在库存中是唯一的,那么“正常”方式是:
SELECT count(*) as total, count(i.product_id) as matches
FROM products p LEFT JOIN
inventory i
ON p.products_id = i.product_id
WHERE p.orders_id = 'xxx';
如果inventory
可以有重复项,那么一个简单的方法是:
SELECT count(distinct p.product_id) as total, count(i.product_id) as matches
FROM products p LEFT JOIN
inventory i
ON p.products_id = i.product_id
WHERE p.orders_id = 'xxx';
编辑:
如果您需要考虑数量:
SUM(CASE WHEN i.qty > 0 THEN 1 ELSE 0 END)
答案 1 :(得分:0)
让我们试试这个
SELECT count(u.Product_id) as total, count(i.product_id) as matches
FROM products p
LEFT JOIN inventory i ON p.products_id = i.product_id
RIGHT JOIN inventory u ON p.products_id = u.product_id
WHERE p.orders_id = 'xxx';