在PHP中搜索和计算数据

时间:2015-07-10 01:25:07

标签: php mysql codeigniter

我想根据月份和年份搜索数据。然后,它将为Book_id计算相同的ID。

我每月计算Book_id都有问题。此查询将计算包括每月在内的整个记录​​,这不是我想要的结果。

$res2 = mysql_query( "SELECT DISTINCT Date_borrow, Book_name as nmBook,   Book_id as b_id,  count(Book_name) AS count 

FROM transaksi

GROUP BY nmBook

HAVING count > 1 

ORDER BY COUNT DESC ");

$rowss = mysql_fetch_array($res2);

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我不知道你完成数据模型

SELECT DISTINCT Date_borrow, Book_name as nmBook,   Book_id as b_id,  
count(Book_name) AS count 
FROM transaksi
GROUP BY nmBook
HAVING count > 1 
ORDER BY COUNT DESC

应该是:

SELECT Date_borrow, Book_name as nmBook,  Book_id as b_id,  
count(Book_name) AS counter
FROM transaksi
GROUP BY Book_name,Date_borrow,book_id
HAVING count(Book_name) > 1 
ORDER BY `counter` DESC;

DISTINCT和GROUP BY是互斥的:一旦你使用GROUP BY,在所有字段上应用一个函数或在GROUP BY中添加字段。

HAVING COUNT(Book_name):COUNT需要一个参数,因此在这种情况下为book_name,因为它与SELECT语句中的相同。

在ORDER BY中使用刚刚创建的别名:测试它。也许你需要在那里使用COUNT(book_name)。

使用保留字" COUNT" as alias:避免在表名,列名,函数名等中使用任何类似于函数或代码的术语。创建自己的命名标准,避免使用(可能)保留的关键字。