MySQL查询总数

时间:2019-02-05 06:16:38

标签: mysql sql

我有三个桌子 enter image description here

enter image description here

enter image description here

我已执行以下查询:

SELECT 
`tbl_players`.`id` AS `player_id`
,`tbl_players`.`player_name`
,`tbl_sports`.`sports_name`
,`tbl_scores`.`score`
FROM `tbl_players`
LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
ORDER BY `tbl_players`.`id` ASC

我得到了: enter image description here

现在我想要这个: enter image description here

5 个答案:

答案 0 :(得分:1)

使用条件聚合

select player_id,player_name,sports_name,
       sum(case when season=1 then score end) as season1_score,
       sum(case when season=2 then score end) as season2_score,
       sum(case when season=3 then score end) as season3_score
from
(
SELECT 
`tbl_players`.`id` AS `player_id`
,`tbl_players`.`player_name`
,`tbl_sports`.`sports_name`
,`tbl_scores`.`score`,`tbl_scores`.`season`
FROM `tbl_players`
LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
)A group by player_id,player_name,sports_name

答案 1 :(得分:1)

使用条件聚合

 SELECT 
    `tbl_players`.`id` AS `player_id`
    ,`tbl_players`.`player_name`
    ,`tbl_sports`.`sports_name`
    , sum(case when tbl_scores.season=1 then `tbl_scores`.`score` end) as season1score
   ,sum(case when tbl_scores.season=2 then `tbl_scores`.`score` end) as season2score
,sum(case when tbl_scores.season=3 then `tbl_scores`.`score` end) as season3score
    FROM `tbl_players`
    LEFT JOIN `tbl_scores` ON `tbl_players`.`id`=`tbl_scores`.`player_id`
    LEFT JOIN `tbl_sports` ON `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
group by `tbl_players`.`player_name`
    ,`tbl_sports`.`sports_name`,player_id

答案 2 :(得分:0)

这可能有帮助。

您需要PIVOT您的数据

SELECT 
 player_id,
 player_name,
 sports_name,
 sum(case when tbl_scores.season=1 then `tbl_scores`.`score` end) as season1score,
 sum(case when tbl_scores.season=2 then `tbl_scores`.`score` end) as season2score,
 sum(case when tbl_scores.season=3 then `tbl_scores`.`score` end) as season3score
from 
  tbl_players
left join  tbl_sports 
  on `tbl_players`.`id`=`tbl_scores`.`player_id`
left join sports 
  on `tbl_players`.`sports_id`=`tbl_sports`.`sports_id`
group by
 layer_id,
 player_name,
 sports_name,

答案 3 :(得分:-1)

使用“与众不同”选择不会重复。

只需在查询中的“ SELECT”之后添加“ DISTINCT”。

示例:SELECT DISTINCT column1,column2,... FROM table_name;

答案 4 :(得分:-1)

我相信您应该使用内部联接而不是左联接