我希望得到作者所写书籍的最大数量与每位作者所写的数量之间的差异。
SELECT count(book_name) contar, (MAX(C.qty) - count(book_name)) final
FROM (select B.author_id, count(book_name) qty
FROM author A ,BOOK B
WHERE A.author_id = B.author_id
GROUP BY b.author_id) C ,
author A,
BOOK B
WHERE A.author_id = B.author_id
AND B.author_id=C.Author_id
AND date_release BETWEEN NOW() - INTERVAL 20 YEAR AND NOW()
GROUP BY c.author_id
HAVING contar > 0
如您所见,有两个表BOOK
包含book_id
,author_id
,book_name
,date_release
和表AUTHOR
{{1 }},author_id
,author_name
,author_lastname
。
我收到了这个结果
但我需要像
这样的东西date_birth
答案 0 :(得分:3)
问题是每个作者正在计算MAX(C.qty)
,因为查询有GROUP BY c.author_id
。您需要为整个子查询计算此总计一次。
由于作者ID位于AUTHOR
,因此在获取每位作者的图书数时,也无需加入BOOK
。
SELECT count(book_name) contar, (max_qty - count(book_name)) final
FROM (SELECT MAX(qty) AS max_qty
FROM (select count(book_name) qty
FROM BOOK B
GROUP BY b.author_id) t
) C
CROSS JOIN author A
JOIN book B ON A.author_id = B.author_id
WHERE date_release BETWEEN NOW() - INTERVAL 20 YEAR AND NOW()
GROUP BY A.author_id
并且不需要HAVING contar > 0
,因为没有书籍的作者将不会包含在JOIN
中。
答案 1 :(得分:2)
试试这个。我将每个数字等于一个变量,然后减去这些变量。然而,变量将作为列出现。
SELECT count(book_name) contar,
@max:=( MAX(C.qty) ),
@bookcount:=( count(book_name) ),
@final:= @max-@bookcount
FROM (select B.author_id,
count(book_name) qty
FROM author A , BOOK B
WHERE A.author_id = B.author_id
GROUP BY b.author_id) C ,
author A,
BOOK B
WHERE A.author_id = B.author_id
AND B.author_id = C.Author_id
AND date_release BETWEEN NOW() - INTERVAL 20 YEAR
AND NOW()
GROUP BY c.author_id
HAVING contar > 0