我正在尝试使用PHP访问MySQL数据库。我需要从我的actor_id
表中检索6个值,在html表中显示它们。我的SELECT语句是:
SELECT actor_id.actor_name, FROM actor_id WHERE movie.star1 = actor_id.actor_id;
现在我该如何添加另一部电影.star2,movie.star3等?
数据库结构
NAME - 字段 电影 - movie_id title star1 star2 actor_id - actor_id actor_name
答案 0 :(得分:2)
从这看起来,你实际上在这里使用两个表。但是,您的查询仅引用其中一个。
我认为你需要这样的东西:
SELECT
actor_id.actor_name,
FROM
actor_id
join movie
on movie.star1 = actor_id.actor_id
or movie.star2 = actor_id.actor_id
or movie.star3 = actor_id.actor_id
-- etc etc
尽管如此,你可能会很好地read this lengthy Q&A that I wrote来更详细地解释这些事情。
答案 1 :(得分:1)
正如我在评论中所说,这很容易(如果你read the manual):
SELECT field1, field2, field3 AS altName, lastFieldNoCommaHere
FROM table
WHERE someField = 'value'
AND id IN (1,2,3,4,5,6,7,8,9)
AND (dateField > NOW()
OR dateField IS NULL);
RTM并且不使用mysql_*
扩展名,它已被弃用。使用PDO
或mysqli_*
,不仅仅是因为弃用问题,But for various reasons。
当您在where子句中使用movie.star1
时,您应该同时查看the JOIN
syntax:
SELECT actor_id.name
FROM actor_id
LEFT JOIN movie
ON movie.star1 = actor_id.actor_id
WHERE actor_id.actor_id IN (1,2,4,5,6,7,8,123);
这可能是你所追求的,或许是:
SELECT actor_id.name
FROM actor_id
WHERE actor_id.actor_id
IN ( SELECT movie.star1
FROM movie
WHERE movie.release_date >= '2012-01-01');
这是子查询的示例。小心这一点,因为它通常很慢......
正如Fluffeh向我指出的那样,你不能选择多个值,并且不得不求助于这样的事情:
SELECT actor_id.name
FROM actor_id
WHERE actor_id.actor_id
IN ( SELECT IFNULL(movie.star1, IFNULL(movie.star2, movie.star3))
FROM movie
WHERE movie.release_date >= '2012-01-01');
或者:
SELECT actor_id.name
FROM actor_id
WHERE actor_id.actor_id
IN ( SELECT IF (movie.star1 <= 12,
IF (movie.star2 <= 15,
movie.star3,
movie.star2),
movie.star1)
FROM movie
WHERE movie.release_date >= '2012-01-01');
答案 2 :(得分:0)
使用或声明。 我不知道您的数据库结构,但应该使用or:
SELECT actor_id.actor_name,
FROM actor_id
WHERE (movie.star1 = actor_id.actor_id or movie.star2 = actor_id.actor_id);
答案 3 :(得分:0)
SELECT actor_id.actor_name
FROM actor_id WHERE actor_id.actor_id in [specify the values like movie.star2, movie.star3... etc];
但不能在FROM之前使用逗号..