我有两张桌子..类别&交易。最终,我想做以下事情:
// foreach category
// Display category title
// show 3 entries in deals where it matches category title above, along with a link saying: "View (count) More Deals
现在,我有几种方法可以做到这一点:
// The "bad" way:
// foreach category
// fetch count of total deals in this category
// Display category title (once)
// Fetch & Display 3 deals
// Display "View (count) more deals
// This is just quite a few queries for one page
“其他”方式:
SELECT count(deals.id),
category.name as category_name,
deal.name as deal_name
FROM $db[ddd_deals] as deals
JOIN $db[ddd_categories]
ON $db[ddd_categories].id = $db[ddd_deals].category_id
WHERE deals.city_id = '$_SESSION[city_id]'
ORDER BY $db[ddd_categories].name
除了显示每个类别中的交易数量之外,上述所有内容都会执行,并且每个类别仅显示3笔交易
- 我应该从交易表中选择(或从类别表中选择,然后获取交易?)
// I also tried the following. It returns what category and deal, but the count is off (it is only displaying 1):
SELECT count(deals.id) as cc,
cat.name as cat_name,
deals.name as name
FROM ddd_categories as cat
JOIN ddd_deals as deals
ON deals.category_id=cat.id
GROUP BY deals.id
ORDER BY cat.id
答案 0 :(得分:0)
您需要GROUP BY cat.id
而不是deals.id
。尝试以下:
SELECT count(deals.id) as cc, cat.name as cat_name, deals.name as name
FROM ddd_categories as cat JOIN ddd_deals as deals ON deals.category_id=cat.id
GROUP BY cat.id
答案 1 :(得分:0)
只是一个快速的,无论你是通过deals.id或..分组,订单来自不正确的地方。
select cc, cat_name, name from (
SELECT count(deals.id) as cc, cat.name as cat_name, deals.name as name
FROM ddd_categories as cat
JOIN ddd_deals as deals on deals.category_id=cat.id
GROUP BY deals.id
)
ORDER BY xxx;