我试图在我的mysql数据库中查询5个单独的表,结构如下;
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 |
目前,我可以加入其中的两个表格并显示我需要的信息,例如一个佩戴它的项目:
$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命令但是我不知道如何使用它?
请告知。
答案 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';