如何在INNER JOIN中显示课程名称?

时间:2018-10-25 20:51:40

标签: php sql yii2

我有两个表:userscourses。在用户表中,我提交了course,其中有课程ID。在课程表中,我只有IDNAME

我需要获得热门课程。我要求:

SELECT u.course, COUNT(*) as freq FROM users u INNER JOIN courses c ON u.course = c.id GROUP BY u.course

结果是:id => freq。但是我当然需要将ID替换为NAME。怎么样?

谢谢。

4 个答案:

答案 0 :(得分:3)

您没有说使用什么数据库,但是我认为您可以使用CTE,因为大多数现代数据库都可以使用。您的查询可以写为:

with x as (
  select course, count(*) as freq from users group by course
),
y as (
  select max(freq) as max_freq from x
)
select c.name, x.freq
  from x
  join y on x.freq = y.max_freq
  join courses c on c.id = x.course

此查询具有[希望的]副作用,如果第一名并发多个,则显示多门课程。

答案 1 :(得分:1)

c.name子句和SELECT子句中都添加GROUP BY

SELECT u.course, c.name, COUNT(*) as freq
FROM users u
INNER JOIN courses c
ON u.course = c.id
GROUP BY u.course, c.name;

演示:https://dbfiddle.uk/?rdbms=mariadb_10.3&fiddle=02a41e0f1e6407e516e91c49b4bdc1d2

答案 2 :(得分:-1)

SELECT u.course, COUNT(*) as freq, c.name FROM users u INNER JOIN courses c ON u.course = c.id GROUP BY u.course

答案 3 :(得分:-1)

如果您的DBMS支持row_number,这将是合适的:

select t.id, c.name, t.cnt  
    from course c
    join (
        select c.id, count(1) cnt, ROW_NUMBER() over(order by count(1) desc) rn
          from users u 
          join course c on c.id = u.course
        group by id
        )t on t.id = c.id and t.rn = 1