2014-02-10 71 views
0

當我想要顯示來自多個數據庫的數據時,我遇到了問題。它給出了重複的值。MYSQL:如何從多個數據庫中選擇DISTINCT

所以我有三個數據庫在同一臺服務器上。他們有相同的表結構。 因此,這裏是我的查詢:

Query = 'SELECT id_movie, movie_tittle 
      FROM (SELECT id_movie, movie_tittle, status from margoplatinum.movie 
     UNION 
     SELECT id_movie, movie_tittle, status from detos21.movie 
     UNION 
     SELECT id_movie, movie_tittle, status from plaza21.movie) AS a 
     WHERE a.status = "Now Playing"' 

它的工作原理,但給這樣的重複值:

id_movies  |  movie_tittle 
------------------------------------------ 
     2  |   THOR 2 
     1  |   Gravity 
     3  |   THOR 2 
     1  | The Legend of Hercules 
     4  |   Gravity 

所以我把DISTINCT條款是這樣的:

Query = 'SELECT id_movie, DISTINCT (movie_tittle) 
      FROM (SELECT id_movie, movie_tittle, status from margoplatinum.movie 
      UNION 
     SELECT id_movie, movie_tittle, status from detos21.movie 
     UNION 
     SELECT id_movie, movie_tittle, status from plaza21.movie) AS a 
     WHERE a.status = "Now Playing"' 

但查詢上面沒有工作。它有一個錯誤信息:

#1064 - You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version 
for the right syntax to use near 'DISTINCT (movie_tittle) 
FROM (SELECT id_movie, movie_tittle, status from mar' at line 1 

那麼如何從多個數據庫中編寫SELECT DISTINCT?

您的任何幫助將是非常有益的:) 謝謝

回答

2

這是您的查詢:

SELECT id_movie, movie_tittle 
FROM (SELECT id_movie, movie_tittle, status from margoplatinum.movie 
     UNION 
     SELECT id_movie, movie_tittle, status from detos21.movie 
     UNION 
     SELECT id_movie, movie_tittle, status from plaza21.movie 
    ) a 
WHERE a.status = 'Now Playing' 

這是返回重複。你在select中有id_movie,這在每個表中(顯然)是不同的。

刪除id_movie,並且它會與沒有重複回到電影的名字:

SELECT movie_title 
FROM (SELECT movie_title, status from margoplatinum.movie 
     UNION 
     SELECT movie_title, status from detos21.movie 
     UNION 
     SELECT movie_title, status from plaza21.movie 
    ) a 
WHERE a.status = 'Now Playing'; 

而且,存儲電影每個影院是一個壞主意,從關係數據庫的角度。你應該把所有的電影放在一張桌子上,以及他們正在玩的電影院裏。

+0

AAH我see..I完全忘記了id_movie..Thank你,先生! :) – Aprilia

0

試試這個

SELECT DISTINCT movie_tittle, id_movie 
FROM 
    (SELECT 
     id_movie, movie_tittle, status 
    from 
     margoplatinum.movie UNION SELECT 
     id_movie, movie_tittle, status 
    from 
     detos21.movie UNION SELECT 
     id_movie, movie_tittle, status 
    from 
     plaza21.movie) AS a 
WHERE 
    a.status = 'Now Playing';