2013-01-16 47 views
2

我目前擁有此代碼。搜索多個mysql表

  switch($search_topic) 
      { 
       case 'Title': 
        $stmt = $dbh->prepare("SELECT game_id, title, platform_name, author_name, price 
              FROM games 
              WHERE title 
              LIKE :search_term"); 
       break; 

       case 'Platform': 
        $stmt = $dbh->prepare("SELECT game_id, title, platform_name, author_name, price 
              FROM games 
              INNER JOIN platforms ON games.platform_id = author.platform_id 
              WHERE platform_name LIKE :search_term"); 
       break; 
      } 

的search_topic變量從先前網頁列表框的到來,標題搜索正常工作作爲其只是簡單地搜索一個MySQL表。由於我試圖搜索多個表,因此平臺搜索正在進行中,這很有意義。

遊戲桌有一個名爲「platform_id」的列,這個列鏈接到平臺表,其中關鍵字段鏈接到它所處的平臺。那麼我怎樣才能從遊戲表中獲取「platform_id」,然後將其鏈接到「平臺」,以便我瀏覽「platform_title」,然後使用它進行搜索。

架構:基於把你的小提琴http://sqlfiddle.com/#!2/3d3e3/6

+0

只是你的連接不好嗎?它應該不是'... ON games.platform_id = platforms.id' – hafichuk

+0

我會*非常*建議您在sqlfiddle.com上使用我們可以玩的數據構建模式 – hafichuk

+0

Well spotted,不按預期工作,謝謝注意! – user1725794

回答

3

,這裏的更新您:

SELECT g.game_id, g.title, p.platform_name, a.author_name, g.price 
FROM games g 
INNER JOIN platforms p ON p.platform_id = g.platform_id 
INNER JOIN author a ON a.author_id = g.author_id 
WHERE g.title LIKE 'Skyrim'; 

你會明顯改變WHERE g.title LIKE 'Skyrim';取其場你想過濾的。因此,該平臺查詢應爲:

SELECT g.game_id, g.title, p.platform_name, a.author_name, g.price 
FROM games g 
INNER JOIN platforms p ON p.platform_id = g.platform_id 
INNER JOIN author a ON a.author_id = g.author_id 
WHERE p.platform_name LIKE 'Xbox'; 

我也建議你改變你的字符集,而不是爲utf8 latin1的,假設這反映了你的生產數據庫的設置。

+0

你明星!它非常完美,非常感謝!如果我想搜索一位作者,是否只是將where語句更改爲a.author_name LIKE'Something'? – user1725794

+0

沒錯。很高興它適合你。 – hafichuk

+0

這樣做很沒有意義,平臺搜索在以前工作。如果我在phpmyadmin上運行該代碼,該代碼仍然有效,並且它顯示正確的結果,但是如果在我的網站上,它將返回不正確的信息。但代碼是一樣的嗎?這可能導致什麼? – user1725794

2
SELECT games.game_id, 
games.title, 
games.platform_name, 
games.author_name, 
games.price, 
games.platform_id, 
platforms.platform_id, 
platforms.platform_name 
FROM games, platforms 
WHERE 
games.platform_id = platforms.platform_id 
AND 
platform.platform_name LIKE %:search_term% 
+1

喜歡pre-SQL92。老套! – hafichuk