2017-10-11 60 views
0

我有2個表MOVIES和SHOWS。從多個表中檢索數據mysql php

MOVIES表包含:

id, name, image, description. 

SHOWS表包含:

id, movieid, description. 

我執行mysql的語句從爲表中檢索記錄,我得到的所有記錄一般。我再次執行另一個mysql語句來從MOVIES表中獲取圖像,這是基於我從第一個查詢獲得的電影表ID。 是否有任何簡單的方法來檢索SHOWS表中的所有記錄以及電影圖像?

這是我的查詢:

$qry1 = mysql_query("SELECT * FROM shows WHERE id='1'"); 
$res = mysql_fetch_array($qry1); 
$movieid = $res['movieid']; 
$qry2 = mysql_query("SELECT image FROM movies WHERE id='$movieid'"); 
+0

文檔中的問題 –

+1

提示提供查詢:'INNER JOIN '。 –

+0

這些是我的查詢 $ qry1 = mysql_query(SELECT * FROM shows WHERE id ='1'); $ res = mysql_fetch_array($ qry1); $ movieid = $ res ['movieid']; $ qry2 = mysql_query(SELECT image FROM movies WHERE id ='$ movieid'); –

回答

1
SELECT t1.id, t1.movieid, t1.description, t2.image FROM SHOWS as t1 
INNER JOIN 
MOVIES as t2 ON t1.id = t2.id 

一些SQL加入docs

,或者你可以試試這個,我不知道女巫ID是從哪兒:

SELECT id, movieid, description, image FROM SHOWS 
INNER JOIN MOVIES 
ON id = movieid 

一些外鍵docs

0

在這裏,我用了寫你一起都可以這樣使用嵌套select查詢

select movies.image from movies where movies.id in(Select shows.movieid form shows where shows.id= 1); 
0

您可以從一臺服務器同時檢索多個表中的數據。有很多方法可以實現這種操作,稱爲join。其中一個可能性將是LEFT JOIN這樣的:

SELECT t1.field1, t1.field2,..., t2.field1, t2.field2, ..., t2.fieldn 
FROM table1 AS t2 
LEFT JOIN talble2 AS t2 ON t2.some_field = t1.anothed_filed 
WHERE some_condition 

在你的情況:

SELECT s.*, m.image 
FROM SHOWS AS s 
LEFT JOIN movies AS m ON s.movieid = m.id 
WHERE some_condition 

更多信息請參見https://dev.mysql.com/doc/refman/5.7/en/join.html