2011-03-24 53 views
2

我有一個數據庫:MySQL選擇流派問題。 (PHP)

id  |    movie_name    |   genres 
1  |     Die Hard    |  Action, Thriller 
2  |    Gladiator    | Adventure, Action, Drama, History 
3  | Harry Potter and the Sorcerers Stone | Fantasy, Adventure, Family 
4  |    Pearl Harbor    |  Action, Melodrama, War 

1)如何我可以從所有的數據庫genres選擇獨特的風格。 我需要下:動作/冒險/劇情/家庭/奇幻/歷史/音樂劇/驚悚/戰爭

2)我怎麼能看電影某一類型?

SELECT `movie_name` FROM `movies` WHERE `genre` LIKE ?? 

但他也不僅能帶來戲劇,還能帶來情節劇。

3)如何搜索特定的流派? 可能是:

SELECT `movie_name` FROm `movies` WHERE `movie_name` LIKE `%stone%` AND `genres LIKE 'drama'. 

對不起,英語不好。謝謝!

回答

4

不要在數據庫列中存儲以逗號分隔的屬性列表。

取而代之的是,有3個表:

Movies (id, movie_name) 

id | movie_name 
---+-------------------------------------- 
1 | Die Hard 
2 | Gladiator 
3 | Harry Potter and the Sorcerers Stone 
4 | Pearl Harbor 

Genres (id, genre_name) 

id | genre_name 
---+------------ 
1 | Action 
2 | Thriller 
3 | Adventure 
4 | Drama 
5 | History 
6 | Fantasy 
7 | Family 
8 | Melodrama 
9 | War 

MovieGenre (movie, genre) 

Movie | Genre 
------+------- 
    1 | 1 
    1 | 2 
    2 | 1 
    2 | 3 
    2 | 4 
    2 | 5 
    3 | 3 
    3 | 6 
    3 | 7 
    4 | 1 
    4 | 8 
    4 | 9 

那麼你的問題變得非常非常簡單。

+1

非常感謝! <3 – Isis 2011-03-24 19:01:36

2

您在這裏遇到的問題是實施N到N關係要求。

由於電影之間的關係是多對多關係,因此將其存儲在數據庫模式中的正確方法是將關係維護在單獨的表中。

爲了這個練習,我們稱這個表爲「Movie_Genre_Relationship」。

Movie_Genre_Relationship 
Movie_id | Genre_id 
1  | 1 
1  | 2 

假設下面的電影和類型表:

Movies 
Movie_id | Movie_Name 
1  | Die Hard 

Genres 
Genre_id | Genre_Name 
1  | Action 
2  | Thriller 

然後可以根據虎膽龍威既是行動&驚悚電影,你應該在關係表中兩行,這樣它存儲搜索所有動作電影做:

select * from Movies m 
inner join Movies_Genres_Relationship r on m.movie_id = r.movie_id 
where r.genre_id = 1 

希望它有幫助。