【问题标题】:Get percentage in sql with multi join使用多连接获取sql中的百分比
【发布时间】:2017-03-24 10:04:09
【问题描述】:

我有 3 个表,我想按 series.title_name 进行分组查询,但我不知道如何获取用户观看的剧集的百分比。
我想要做的是让 user_watched 表中所有观看的剧集乘以 100,然后除以 series 表中该系列的所有剧集。

这是我的桌子:

表格系列(所有系列都存储在这里)

标识 |标题名 | first_air_date |情节

表剧集(所有剧集都存储在这里)

标识 | series_id |季节ID | air_date

table users_watched(所有观看的剧集都存储在这里)

标识 |用户 ID | series_id | type_id(剧集id)|类型名称(剧集)|季节ID



这是我的代码:

SELECT name_table.*, uw.series_id, COUNT(ep.id) all_epi, COUNT(uw.series_id) watched,
       ROUND(COUNT(uw.series_id) *100 / COUNT(ep.id)) percentage
FROM series name_table
    LEFT JOIN users_watched uw ON uw.series_id = name_table.id
    LEFT JOIN episodes ep ON ep.id = uw.type_id
WHERE uw.type_name = 'episodes'
GROUP BY name_table.title_name
ORDER BY percentage DESC



我得到的结果:

array(2) { [0]=> object(stdClass)#28 (39) { ["id"]=> string(1) "7" ["title_name"]=> string(15) "Game of Thrones" ["created_by"]=> string(26) "David Benioff, D. B. Weiss" ["first_air_date"]=> string(10) "2011-04-17" ["last_air_date"]=> NULL ["airs_day_ofweek"]=> string(6) "Sunday" ["airs_time"]=> string(8) "21:00:00" ["year_released"]=> NULL ["plot"]=> string(715) "Il y a très longtemps, à une époque oubliée, une force a détruit l'équilibre des saisons. Dans un pays où l'été peut durer plusieurs années et l'hiver toute une vie, des forces sinistres et surnaturelles se pressent aux portes du Royaume des Sept Couronnes. La confrérie de la Garde de Nuit, protégeant le Royaume de toute créature pouvant provenir d'au-delà du Mur protecteur, n'a plus les ressources nécessaires pour assurer la sécurité de tous. Après un été de dix années, un hiver rigoureux s'abat sur le Royaume avec la promesse d'un avenir des plus sombres. Pendant ce temps, complots et rivalités se jouent sur le continent pour s'emparer du Trône de fer, le symbole du pouvoir absolu." ["genre"]=> string(56) "Action & Adventure, Drame, Science-Fiction & Fantastique" ["homepage"]=> string(34) "http://www.hbo.com/game-of-thrones" ["tagline"]=> NULL ["poster"]=> string(31) "3iYNC7Iw6a65ed5GZz7KbInSHBd.jpg" ["background"]=> string(31) "mUkuc2wyV9dHLG0D0Loaw5pO2s8.jpg" ["episode_run_time"]=> string(2) "60" ["number_of_episodes"]=> string(2) "61" ["number_of_seasons"]=> string(1) "7" ["trailer"]=> NULL ["network"]=> string(3) "HBO" ["budget"]=> NULL ["earnings"]=> NULL ["box_office"]=> NULL ["tmdb_id"]=> string(4) "1399" ["thetvdb_id"]=> string(6) "121361" ["original_title"]=> string(15) "Game of Thrones" ["original_lang"]=> string(2) "en" ["origin_country"]=> string(2) "US" ["production_company"]=> string(62) "Home Box Office (HBO), Generator Entertainment, Television 360" ["production_country"]=> NULL ["certification"]=> NULL ["status"]=> string(16) "Returning Series" ["in_production"]=> string(1) "1" ["fully_scraped"]=> string(1) "1" ["creation_date"]=> string(19) "2017-03-12 14:17:17" ["update_date"]=> string(19) "2017-03-17 18:47:52" ["series_id"]=> string(1) "7" ["all_epi"]=> string(2) "74" ["watched"]=> string(2) "74" ["percentage"]=> string(3) "100" } [1]=> object(stdClass)#29 (39) { ["id"]=> string(3) "179" ["title_name"]=> string(13) "The Last Ship" ["created_by"]=> string(27) "Hank Steinberg, Steven Kane" ["first_air_date"]=> string(10) "2014-06-22" ["last_air_date"]=> NULL ["airs_day_ofweek"]=> string(6) "Sunday" ["airs_time"]=> string(8) "21:00:00" ["year_released"]=> NULL ["plot"]=> string(561) "Après avoir passé plusieurs mois en Arctique pour une mission top secrète, l'équipage de l'USS Nathan James, un destroyer de la NAVY, découvre avec horreur qu'une épidémie a décimé une majeure partie de la population terrestre. La Chine et l'Europe sont en guerre, tandis que le Gouvernement Américain n'est plus. Protégés par les océans, le commandant et les 200 âmes sous ses ordres font partie des derniers survivants de la planète. Une scientifique présente à bord doit absolument trouver un vaccin avant l'extinction totale de l'espèce..." ["genre"]=> string(30) "Action, Drame, Science-Fiction" ["homepage"]=> string(48) "http://www.tntdrama.com/shows/the-last-ship.html" ["tagline"]=> NULL ["poster"]=> string(31) "rTSuFGhBDqxvEDgzNkF2yCwBLr9.jpg" ["background"]=> string(31) "20txnfxxmpvqOdDqIiy2hO06qqG.jpg" ["episode_run_time"]=> string(2) "45" ["number_of_episodes"]=> string(2) "36" ["number_of_seasons"]=> string(1) "3" ["trailer"]=> NULL ["network"]=> string(3) "TNT" ["budget"]=> NULL ["earnings"]=> NULL ["box_office"]=> NULL ["tmdb_id"]=> string(5) "60802" ["thetvdb_id"]=> string(6) "269533" ["original_title"]=> string(13) "The Last Ship" ["original_lang"]=> string(2) "en" ["origin_country"]=> string(2) "US" ["production_company"]=> string(55) "Platinum Dunes, TNT Originals, Channel Road Productions" ["production_country"]=> NULL ["certification"]=> NULL ["status"]=> string(16) "Returning Series" ["in_production"]=> string(1) "1" ["fully_scraped"]=> string(1) "1" ["creation_date"]=> string(19) "2017-03-12 14:25:12" ["update_date"]=> string(19) "2017-03-12 14:51:11" ["series_id"]=> string(3) "179" ["all_epi"]=> string(1) "1" ["watched"]=> string(1) "1" ["percentage"]=> string(3) "100" } }

【问题讨论】:

  • MySQL?该 GROUP BY 无效。将在较新的 MySQL 版本上引发错误(除非在兼容模式下),并在较旧的 MySQL 版本上返回不可预测的结果。一般的 GROUP BY 规则说:如果指定了 GROUP BY 子句,则 SELECT 列表中的每个列引用必须要么标识一个分组列,要么是一个集合函数的参数。
  • 好的,那我该如何使用呢?
  • 您应该包括样本数据和所需的结果。
  • 很抱歉,这对我没有帮助。

标签: php sql


【解决方案1】:

每个用户观看剧集的百分比的查询如下:

select uw.user_id, uw.series_id, s.title_name
    , uw_count * 100 / total_ep as percentage
from (
    select user_id, series_id, COUNT(*) as UW_COUNT
    from user_watched
    group by user_id, series_id
    ) uw
join series s on uw.series_id = s.id
join (
    select series_id, COUNT(*) as total_ep 
    from episodes
    group by series_id) t
on t.series_id = s.id
;

【讨论】:

  • @BenfMaappy,我已经编辑了查询并为剧集表添加了缺少的 group by 子句。现在,它产生了预期的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 2021-11-28
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多