三个表之间的SQL查询

时间:2017-01-05 14:40:12

标签: mysql sql join

这是我正在制作的电影租赁平台的基本摘录。为了告诉你,我只需要这三个表。

胶片

Title        | Genre         |
-------------+---------------+
Why Me       | Romantic      |
The ET       | Fantasy       |
...          | ...           |
Planet       | Documentary   |

用户

ID           | Name          |
-------------+---------------+
213          | Jonh D        |
34267        | Smith E       |
...          | ...           |
256          | Sally F       |

出租

User_ID      | Film_Title    | Date        |
-------------+---------------+-------------+
34267        | The ET        | 2015-11-01  |
256          | Planet        | 2014-12-03  |
...          | ...           | ...         |
256          | Why Me        | 2016-03-04  |

那就是说,我需要做一个SQL查询,该查询与每个Film.Genre User.Name关联,这些ID | Genre | -------------+---------------+ Sally F | Romantic | Smith E | Fantasy | ... | ... | Sally F | Documentary | 已经为该类型租了最多的电影。

JOIN

我会发布我的一些尝试,但老实说,我没有提出任何几乎没有意义的事情。我知道使用SELECT u.Name, f.Genre FROM User AS u JOIN Rent AS r JOIN Film AS f GROUP BY f.Genre ORDER BY(COUNT(r.User_ID)) 语句会更容易尝试用嵌套语句构建它但我很难过,这太令人沮丧了。

mapped[coln].replace(str(val), str(map))

2 个答案:

答案 0 :(得分:1)

这假设类型字段位于您的租借表中:

select user_id, genre, max(rentals) from
(select 
    user_id,
    genre, 
    count(*) as rentals 
 from rent group by user_id, genre)
 group by user_id, genre;

答案 1 :(得分:0)

你可以使用像这样的子查询:

@Test
public void testConcat() throws Exception {
    final Iterable<Integer> it1 = asList(1, 2, 3);
    final Iterable<Integer> it2 = asList(4, 5);
    int j = 1;
    for (final int i : concat(it1, it2)) {
        assertEquals(j, i);
        j++;
    }
}