我有以下 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/