php - Mysql - 带计数项的子查询

标签 php mysql

我有 2 个表 .. 类别和交易。最后,我想执行以下操作:

// 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

最佳答案

快点,无论您是按 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;

关于php - Mysql - 带计数项的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7212681/

相关文章:

php - PDO 插入错误

PHP如何显示纯URL

mysql - 从点表中使用 MySQL 查找最近的点

mysql - 按不同分类法中的标签进行选择(AND + OR)

mysql - 如何将现有数据库导入到我的 db.py 模型中?

php - 退出函数的标准

php - Twitter API 返回错误 215,错误的身份验证数据

PHP 可用性[]\用 mySQL 查询

php - Laravel:表格更新表中的多行?

mysql - 对于列出的类别,获取可用优惠列表