php - 具有适当计数的双重查询

标签 php mysql

恐怕我写了一个查询并在这个过程中弄糊涂了,尽管它很简单。

我有 2 个 mysql 表。

Table1 has ... orderID, productID, quantity
Table2 has ... orderID, status, time

我需要执行一个查询来执行以下操作......

Output (1 per line) 
productID - Quantity  where status = 1 & time < $lastactive. 

我尝试对表 2 进行查询以获取 productID 并计算数量,但如果 2 个不同的 orderID 具有相同的 productID,则它不会对它们求和。非常感谢任何帮助(表/行的名称是准确的)。

例子:

orderID 123, productID 2, quantity 4
orderID 123, productID 5, quantity 6
orderID 678, productID 2, quantity 5

会输出:

2   9
5   6

最佳答案

你应该能够使用类似这样的东西:

select t1.productId, Sum(t1.quantity) Total
from table1 t1
inner join table2 t2
  on t1.orderid = t2.orderid
where t2.status = 1
  and t2.time < $lastactive
group by t1.productid

关于php - 具有适当计数的双重查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13571807/

相关文章:

mysql - 查找父级、子级及其子级的层次结构树 - MySQL 查询

php - PHP 中的条件切换语句

php - preg_replace div(或任何东西)与 class=removeMe

java - Openshift Tomcat Mysql Javascript 连接字符串

mysql - 启动 mysql 服务器 docker 容器时出现问题 - 无法通过 "Initializing database"

mysql - 建立数据库连接时出错

Python pymysql 无法接受密码字符串中的特殊字符,如何绕过这个?

PHP 返回在 Ubuntu 上不起作用

javascript - 如何以可绘图格式输出 PHP 结果

php - 代码点火器 : Problem inserting accents in Mysql