In MySQL, how to "join" three tables
I've seen a good amount of threads on "how to join more than two tables" but none of those threads seem to solve my problem. I have three tables: teams, persons and payfiles
teams Table looks like this:
DROP TABLE IF EXISTS `teams`; CREATE TABLE IF NOT EXISTS `teams` ( `team_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `leader` varchar(32) NOT NULL, PRIMARY KEY (`team_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=30;`
DROP TABLE IF EXISTS `persons`; CREATE TABLE IF NOT EXISTS `persons` ( `team_id` int(2) DEFAULT '0', `hash` varchar(32) NOT NULL, UNIQUE KEY `hash` (`hash`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `payfiles`; CREATE TABLE IF NOT EXISTS `payfiles` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hash` varchar(32) NOT NULL, `deals_passed` int(2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1298 ;
Tables have much more columns, but I trimmed them for the sake of simplicity.
teams table contains records in the following way: 1,Team 1,afaf7878af78a The latter is the team leader's unique hash.
The table persons contains all the personal information, and a unique hash, For instance John Doe whose hash is afaf7878af78a who also is the leader of Team 1.
The table payfile also has a "hash" column, that table contains all the information needed to compute employees' checks.
The management team want a general vision of how much the company is making. They want to see how much money every single team is bringing in.
The problem I'm facing here, is trying to group the earnings by "teams"
My best try so far is this
SELECT hash, SUM(deals_passed) as deals FROM payfiles JOIN persons ON persons.hash = payfiles.hash GROUP BY payfiles.hash
but I can't see an optimized way to query the database in order to generate a team by team general vision of earnings without changing the structure of the database.
For instance: John Doe, and Jane Doe belong to "Team 1" and they brought in $500 and $600 respectively.
I want to generate something like:
"Team 1 brought in $1100"
My alternative is to change the structure of the database, and add a new column to the payfile table. Such column would be team_id so I can query it easily, but the database currently has about 10,000 records so that implies updating the 10K records that didn't consider a team_id column, and make a lot of changes to the GUI, something that I don't really want to do, although if that's the easiest and best option I'll do it.
SELECT teams.name, SUM(payfiles.deals_passed) AS team_deals_passed FROM payfiles LEFT JOIN persons USING (hash) LEFT JOIN teams USING (team_id) GROUP BY teams.team_id
You can use SUM() to the get the total, and use GROUP BY for the team to get each total by team.