我有两个具有以下结构的表 表A
itemId categoryId orderDate
==========================================
1 23 2016-11-08
1 23 2016-11-12
1 23 2016-11-16
表B有结构
categoryId stock price
==========================================
23 500 600
但是我想要的输出应该是这样的 结果 C
price stock orderdate qty
600 500 2016-11-08 (first order date) 3 (3 time appearance in first table)
这是我到目前为止尝试过的
select b.price,b.stock from B b, A a
where b.categoryId = (
select a.categoryId
from A
GROUP BY categoryId
HAVING COUNT(categoryId)>1
)
and (a.orderdate = (
select MIN(orderdate)
from A
where categoryId = b.categoryId)
)
我有以下结果
price stock orderdate
600 500 2016-11-08
我不知道如何找到 qty
,因为它在第一个表中出现了 3 次。
最佳答案
我认为您希望表 a 中的记录按项目 ID 和类别 ID 分组,因此将这两个包含在您的 group by 语句中。然后,您必须使用 MIN、MAX、AVG、SUM 等聚合其他列。我使用 MIN,它将为您提供该特定列组中的最小数字,尽管在这种情况下您是否使用 MIN 无关紧要或 MAX 或 AVG - 都是一样的。然后 COUNT(*) 将只计算组中记录的数量。
此外,与使用逗号列出表相比,连接通常更受欢迎。
SELECT a.itemid, a.categoryid, MIN(b.price), MIN(b.stock), min(a.orderdate), count(*) as qty
FROM a
INNER JOIN b ON a.categoryid = b.categoryid
GROUP BY a.itemid, a.categoryid
关于mysql - 如何使用多个表之间的连接优化sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40640190/