php - 查找给定位置的记录总数

标签 php mysql aggregate

我有以下 mysql 查询:

SELECT sku, quantity, inventory.isbn13, author, title, pub_date, binding, 
      defect.defect, source, location from inventory
      LEFT JOIN location ON inventory.location_id = location.location_id
      LEFT JOIN source ON inventory.source_id = source.source_id
      LEFT JOIN book ON inventory.isbn13 = book.isbn13
      LEFT JOIN defect ON inventory.defect_id = defect.defect_id
      LEFT JOIN book_condition ON book_condition.condition_id = defect.condition_id
      WHERE quantity > '0' and location.location_id >= '986' and location.location_id <= '989'
      ORDER BY inventory.location_id, sku

效果很好,但现在我需要显示每个位置 ID 的图书总数。例如 location_id 986 有 17 本书,location_id 987 有 34 本书等。 我是否需要运行第二个查询来获取此信息,或者有没有办法在我的查询中执行此操作?
谢谢 吉姆

最佳答案

给你:

SELECT
    sku, 
    quantity, 
    inventory.isbn13, 
    author, 
    title, 
    pub_date, 
    binding, 
    defect.defect, 
    source, 
    location,
    t.cnt
FROM 
    inventory i
        INNER JOIN 
            (
            SELECT
                inventory.location_id,
                COUNT(book.isbn13) as `cnt`
            FROM inventory
                  LEFT JOIN book ON inventory.isbn13 = book.isbn13
            GROUP BY inventory.location_id
            ) t ON t.location_id = i.location_id
        INNER JOIN location l       ON i.location_id = l.location_id
        LEFT JOIN source            ON i.source_id = source.source_id
        LEFT JOIN defect            ON i.defect_id = defect.defect_id
        LEFT JOIN book_condition    ON book_condition.condition_id = defect.condition_id
WHERE 
    i.quantity > '0' 
AND l.location_id >= '986' 
AND l.location_id <= '989'

关于php - 查找给定位置的记录总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899818/

相关文章:

mysql - 有没有更好的MySql查询

r - 简化多个一对一配对聚合

r - 聚合函数错误

php - 在外部网站上自动填写和提交表格

javascript - 播放另一个视频时停止视频

php - 复制后损坏的图像

python - 极坐标相当于 pandas groupby.apply(drop_duplicates)

php - 使用 MySQL 的 CGI : How to display all data from table?

来自 3 个表的 MySQL 查询(计数)

mysql - 将 HQL 与 MySQL 结合使用,如何在分组依据之前对结果集进行排序,以便选择正确的记录?