我需要根据生成的获取表来计算列数。我试图将它组合成1个查询而不是将其分开。
我在下面的图片提供了更好的说明。假设我在PostTable
内有1000条记录,并且我想根据PostTable.DateTime
检索最新的20条记录。我对此没有任何问题。
但根据检索到的20条记录,我想做一个COUNT
函数来计算发现LikeID
存在时ImageID
出现的次数。
SELECT PostTable.PostID, PostTable.UserID, COUNT(LikeID), PostTable.DateTime
FROM PostTable, LikeTable
WHERE PostTable.ImageID = LikeTable.ImageID
AND LikeTable.LikeID = ?????? // I'm stuck here
答案 0 :(得分:0)
你需要分组,所以试试这个:
function getItems(itemKeys, itemSortOrders, itemsMap)
{
var items = _.map(itemKeys, function(itemKey, index) {
var item = itemsMap[itemKey];
return _.extend({
key: itemKey,
title: item.title,
imageURL: item.imageURL,
formattedPrice: utils.formatMoney(item.price),
producerKey: item.producerKey,
producerTitle: item.producerTitle,
allowOrder: true,
sortOrder: itemSortOrders[index]
}, calculateItemDetails(item.deliveryDayAvailable, item.deliveryDayStatus, item.deliveryDayUsageCount));
});
items = _.compact(items);
return items;
}
详细了解分组:https://dev.mysql.com/doc/refman/5.1/en/group-by-handling.html
哦,考虑一下更现代的JOIN语法:
SELECT PostTable.PostID, PostTable.UserID, COUNT(LikeID) LikeCount, PostTable.DateTime
FROM PostTable, LikeTable
WHERE PostTable.ImageID = LikeTable.ImageID
GROUP BY PostTable.PostID, PostTable.UserID, PostTable.DateTime
HAVING COUNT(LikeID) > 0
@sagi ^^^;)
简化示例
SELECT pt.PostID, pt.UserID, COUNT(lt.LikeID) LikeCount, pt.DateTime
FROM PostTable pt
LEFT JOIN LikeTable lt ON pt.ImageID = lt.ImageID -- Note it's a left join now
GROUP BY pt.PostID, pt.UserID, pt.DateTime
HAVING COUNT(lt.LikeID) > 0
这是你正在寻找的一个例子吗?