使用mysql存储过程中的feching表获取表信息

时间:2015-07-08 03:20:30

标签: php mysql stored-procedures

帮助...

我有两张桌子,

客户

id | registration_code | full_name
 1 | A01               | ABC
 2 | B01               | BCD
 3 | C01               | CDE
 4 | D01               | DEF

history_transaction

id | customer_id | transaction_date
 1 | 1           | 2015-01-01
 2 | 2           | 2015-01-01
 3 | 3           | 2015-01-01
 4 | 1           | 2015-01-02
 5 | 3           | 2015-01-02
 6 | 1           | 2015-01-03

我使用PHP,我希望获得2015-01-01至2015-01-03之间的客户列表和交易时间

结果应该是

id | registration_code | full_name | n_trans
 1 | A01               | ABC       | 3
 2 | B01               | BCD       | 1
 3 | C01               | CDE       | 2

请帮忙。我想在MySQL上使用Store Procedure,我不想在PHP中循环它。

2 个答案:

答案 0 :(得分:1)

要获取您使用group by语句的信息:

SELECT a.id,a.registration_code,a.full_name, COUNT(*) as n_trans
FROM customers a
INNER JOIN history_transaction b 
ON a.id=b.customer_id
WHERE b.transaction_date BETWEEN "{start_date}" AND "{end_date}"
GROUP BY a.id,a.registration_code,a.full_name;

你可以使用mysqli动态设置start_date和end_date(一个用于从php处理MySQL的php模块)。

答案 1 :(得分:1)

这是在MySQL中创建存储过程的方法:

CREATE PROCEDURE find_transaction_detail() 开始     选择a.id,a.registration_code,a.full_name,COUNT(*)作为n_trans     来自客户a     INNER JOIN history_transaction ON a.id = b.customer_id     在哪里b.transaction_date BETWEEN" {start_date}" AND" {end_date}"     GROUP BY a.id,a.registration_code,a.full_name; END;

找到结果的方法:

CALL find_transaction_detail();