Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php MySQL-查找两个表中的匹配项(如6/9)_Php_Mysql_Sql - Fatal编程技术网

Php MySQL-查找两个表中的匹配项(如6/9)

Php MySQL-查找两个表中的匹配项(如6/9),php,mysql,sql,Php,Mysql,Sql,我需要计算出两个表之间的匹配数 目前,我正在使用这个查询,它会导致找到匹配项的次数 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

我需要计算出两个表之间的匹配数

目前,我正在使用这个查询,它会导致找到匹配项的次数

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。我该怎么做?

如果产品在库存中是唯一的,那么“正常”方式是:

如果
库存
可以有重复项,那么一个简单的方法是:

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)

如果产品在库存中是唯一的,“正常”方式是:

如果
库存
可以有重复项,那么一个简单的方法是:

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)
让我们试试这个

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';
让我们试试这个

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';

如果数量大于等于1,我如何修改它以确保它只计算I.product\u id?@DennisA…
count(I.product\u id)
只统计库存中的匹配项。因此,它基本上是这样做的。问题是,表中的数量可以是0-这不是一个问题吗?如果数量>=1,我如何修改它以确保它只统计I.product\u id?@DennisA…
计数(I.product\u id)
只统计库存中的匹配项。因此,它基本上是这样做的。问题是,表中的数量可以是0-这不是问题吗?