2011-07-21 35 views
0

我想查询我的mysql数据库中的5个单独的表,结构如下;使用mysql查询多个表

item 
itemid | item | description | brand | date | time | path | 

actor 
actorid | name | actorthumb | bio | 

brand 
brandid | brandname | description | image | 

movie 
movieid | title | genre | year | moviethumb | synopsis| 

request 
requestid | userid | itemid | brandid | movieid | actorid | content | requestdate | 


目前我可以加入表2显示我需要的信息,例如一个项目,谁穿它:

$query = "SELECT * FROM actor, request WHERE actor.actorid = request.actorid and itemid = ".$itemid; 

和什么电影,使用

$query = "SELECT distinct * FROM movie, request WHERE movie.movieid = request.movieid and itemid = ".$itemid; 


但是,我需要写1个查询,将显示所有5个表中的数据,我可以显示我需要的从这些。

我想我需要使用JOIN命令,但我不知道如何使用它?

请指教。

+3

您是否阅读过[加入MySQL文档](http://dev.mysql.com/doc/refman/5.0/en/join.html)? –

+1

所以你有点找“Clue,电影,克里斯托弗Plummer主演的芥末上校,在烛台的研究(由蒂凡尼)”? –

+0

是的理想情况下,我想展示一件物品,穿在哪部电影中,穿着它的演员以及物品的品牌等。 –

回答

2

这是一个非常简单的查询结构,向您展示如何使用它们的id引用不同的表。它可以根据结果在大大提高你想

SELECT 
i.*, /* This will display all the fields in the item table */ 
a.*, /* This will display all the fields in the actor table */ 
b.*, /* This will display all the fields in the brand table */ 
m.*, /* This will display all the fields in the movie table */ 
r.* /* This will display all the fields in the request table */ 
FROM item AS i, actor AS a, brand AS b, movie AS m, request AS r 
/* This joins the request table itemid with the item table itemid */ 
WHERE r.itemid = i.itemid 
/* This joins the request table actorid with the actor table actorid */ 
AND r.actorid = a.actorid 
/* This joins the request table brandid with the brand table brandid */ 
AND r.brandid = b.brandid 
/* This joins the request table movieid with the movie table movieid */ 
AND r.movieid = m.movieid 

如果你想返回更筛选的结果集,你可以添加这样的事情:

/* Or whatever the id is */ 
AND r.requestid = 123 

例子:

SELECT 
i.item, i.description, i.brand, /* item table */ 
a.name, /* actor table */ 
b.brandname, b.description, b.image, /* brand table */ 
m.title /* movie table */ 
FROM item AS i, actor AS a, brand AS b, movie AS m, request AS r 
/* This joins the request table itemid with the item table itemid */ 
WHERE r.itemid = i.itemid 
/* This joins the request table actorid with the actor table actorid */ 
AND r.actorid = a.actorid 
/* This joins the request table brandid with the brand table brandid */ 
AND r.brandid = b.brandid 
/* This joins the request table movieid with the movie table movieid */ 
AND r.movieid = m.movieid 
AND a.name = 'Rosie Huntington-Whiteley';