I have what may be a basic performance question. I've done a lot of SQL queries, but not much in terms of complex inner joins and such. So, here it is:
I have a database with 4 tables, countries, territories, employees, and transactions.
The transactions links up with the employees and countries. The employees links up with the territories. In order to produce a required report, I'm running a PHP script that processes a SQL query against a mySQL database.
SELECT trans.transactionDate, agent.code, agent.type, trans.transactionAmount, agent.territory
FROM transactionTable as trans
INNER JOIN
(
SELECT agent1.code as code, agent1.type as type, territory.territory as territory FROM agentTable as agent1
INNER JOIN territoryTable as territory
ON agent1.zip=territory.zip
) AS agent
ON agent.code=trans.agent
ORDER BY trans.agent
There are about 50,000 records in the agent table, and over 200,000 in the transaction table. The other two are relatively tiny. It's taking about 7 minutes to run this query. And I haven't even inserted the fourth table yet, which needs to relate a field in the transactionTable (country) to a field in the countryTable (country) and return a field in the countryTable (region).
So, two questions:
Where would I logically put the connection between the transactionTable and the countryTable?
Can anyone suggest a way that this can be quickened up?
Thanks.
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `territoryTable` ADD INDEX `territorytable_idx_zip` (`zip`);
ALTER TABLE `transactionTable` ADD INDEX `transactiontable_idx_agent` (`agent`);
SELECT
trans.transactionDate,
agent.code,
agent.type,
trans.transactionAmount,
agent.territory
FROM
transactionTable AS trans
INNER JOIN
(
SELECT
agent1.code AS code,
agent1.type AS type,
territory.territory AS territory
FROM
agentTable AS agent1
INNER JOIN
territoryTable AS territory
ON agent1.zip = territory.zip
) AS agent
ON agent.code = trans.agent
ORDER BY
trans.agent