mysql - SQL Joining rows after using count -


i trying display list of players team #1 , stats go them, here tables

table 1: players

╔═══════════════════════════╗ ║ id | fname | lname | team ║ ╠═══════════════════════════╣ ║ 1 | jason | mcfee | 1     ║ ║ 2 | john | smith  | 1     ║ ║ 3 | jack | doe    | 1     ║ ║ 4 | wayne | gretzky | 2   ║ ╚═══════════════════════════╝ 

table 2: events_goals

╔═════════════════════════╗ ║ id  g_id  a1_id  a2_id  ║ ╠═════════════════════════╣ ║ 1   1  2  3             ║ ║ 2   3  1  2             ║ ║ 3   2  1  null          ║ ╚═════════════════════════╝ 

what want this
name - being concat table
goals - count times player id in g_id column
assists - count (a1_id) + count (a2_id) times playerid in either of columns
points - sum of goals + assists

╔══════════════════════════════════════╗ ║ id | name | goals | assists | points ║ ╠══════════════════════════════════════╣ ║ 1   j.mcfee    1      2          3   ║ ║ 2   j.smith    1      2          3   ║ ║ 3   j.doe      1      1          2   ║ ╚══════════════════════════════════════╝ 

what have tried do

>select id, >concat_ws(', 'substr(fname, 1, 1), lname) name, >from players  >where teamid = 1 

this gets me return of names of players on team id of 1 there names in proper format no problem.

i can count of single player using

>select count(g_id) events_goals id = (playerid) 

this returns correct number of goals player

however when go put stats wrong , displays 1 row when know there supposed three

> select a.id, > concat_ws(', 'substr(a.fname, 1, 1), a.lname) name, > (count(b.g_id))goals,  > (count(c.a1_id))a1,  > (count(d.a2_id))a2  > players > left join events_goals b on a.id = b.g_id  > left join events_goals c on a.id = c.a1_id  > left join events_goals d on a.id = d.a2_id teamid = 1 

this query you're looking for:

select   p.id,   concat_ws(', ', substr(p.fname, 1, 1), p.lname) name,   coalesce(eg_goals.goals, 0) goals,    coalesce(eg_assists1.assists, 0) + coalesce(eg_assists2.assists, 0) assists,   coalesce(eg_goals.goals, 0) + coalesce(eg_assists1.assists, 0) + coalesce(eg_assists2.assists, 0) points players p left join (   select g_id, count(g_id) goals events_goals   group g_id ) eg_goals on p.id = eg_goals.g_id left join (   select a1_id, count(a1_id) assists events_goals   group a1_id ) eg_assists1 on p.id = eg_assists1.a1_id left join (   select a2_id, count(a2_id) assists events_goals   group a2_id ) eg_assists2 on p.id = eg_assists2.a2_id p.team = 1 

you should reconsider redesigning schema. having "events" mixed in same table lead horrible , hard maintain queries.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -