简体   繁体   English

对于大型数据库,MySQL Left Join 1结果

[英]MySQL Left join 1 result for very big DataBase

I have a big database of movies and I want to search movies by years and genres. 我有一个大型的电影数据库,我想按年份和类型搜索电影。

I have 3 table to deal with: 我有3张桌子要处理:

1. movies (Key TITLE_ID)
2. movie2genre (TITLE_ID + GENRE_ID)
3. genre (Key GENRE_ID)

movies: 电影:

+----------+---------------+------+
| TITLE_ID |     TITLE     | YEAR |
+----------+---------------+------+
|  10001   | Matrix        | 1999 |
|  10002   | Walk on Water | 2004 |
+----------+---------------+------+

movie2genre: movie2genre:

+----------+----------+
| TITLE_ID | GENRE_ID |
+----------+----------+
|  10001   |    1     |
|  10001   |    2     |
|  10002   |    2     |
|  10002   |    4     |
|  10001   |    3     |
+----------+----------+

genre: 类型:

+----------+-----------+
| GENRE_ID | GENRE_TXT |
+----------+-----------+
|    1     | Action    |
|    2     | Adventure |
|    3     | Thriller  |
|    4     | Fantasy   |
+----------+-----------+

A user sends a request for year 1999, genre Adventure or Thriller. 用户发送的是1999年类型的冒险或惊悚片的请求。

How can I find all movies in 1 optimized query? 如何在1个优化查询中查找所有电影?

Result should be: 结果应为:

+----------+--------+------+-----------+
| TITLE_ID | TITLE  | YEAR | GENRE_TXT |
+----------+--------+------+-----------+
|  10001   | Matrix | 1999 |  Action   |
+----------+--------+------+-----------+

I don't care which genre gets selected, only that this movie as 1 of genres user ask for. 我不在乎选择哪个流派,只是该电影作为流派之一的用户要求。

You can try joining together the 3 tables and then restricting the query with a WHERE clause using your requirements for year and movie genre. 您可以尝试将3个表连接在一起,然后使用对年份和电影类型的要求通过WHERE子句限制查询。 The query below will return only one record, which you specified would be acceptable. 下面的查询将仅返回一条记录,您指定的记录是可接受的。

SELECT m.TITLE_ID, m.TITLE, m.YEAR, g.GENRE_TXT
FROM movies m
INNER JOIN movie2genre mg ON m.TITLE_ID = mg.TITLE_ID
INNER JOIN genre g ON mg.GENRE_ID = g.GENRE_ID
WHERE m.YEAR = 1999 AND g.GENRE_TXT IN ('Adventure', 'Thriller')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM