从mysql表中查找相关数据

时间:2011-07-17 07:24:23

标签: php mysql

这是我的db

的两个表结构
-- Table structure for table `gf_actor`


CREATE TABLE IF NOT EXISTS `gf_actor` (
  `actor_id` bigint(20) NOT NULL auto_increment,
  `actor_name` varchar(100) default NULL,
  PRIMARY KEY  (`actor_id`),
  UNIQUE KEY `actor_name` (`actor_name`)
) ENGINE=MyISAM;



-- Table structure for table `gf_film_actor`

CREATE TABLE IF NOT EXISTS `gf_film_actor` (
  `film_id` int(20) NOT NULL,
  `actor_id` int(20) NOT NULL,
  KEY `film_id` (`film_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

所以我需要一个查询,它从gf_actor表中获取五个相关的演员名称和id,他们扮演的是由actor_id执行的电影,让我们说actor_id = 1,电影必须是不同的,这意味着五个相关演员必须在与actor_id = 1

的不同电影

2 个答案:

答案 0 :(得分:0)

试试这个

select ga.actor_id, actor_name from gf_actor ga inner join gf_film_actor gf on ga.actor_id = gf.actor_id where gf.film_id in (select gf1.film_id from gf_film_actor gf1 where  gf1.actor_id=1) AND gf.actor_id != 1 LIMIT 5

答案 1 :(得分:0)

你有错误的表格结构。应该是这样的:

CREATE TABLE IF NOT EXISTS `gf_actor` (
  `actor_id` bigint(20) NOT NULL auto_increment,
  `actor_name` varchar(100) default NULL,
  PRIMARY KEY  (`actor_id`),
  UNIQUE KEY `actor_name` (`actor_name`)
) ENGINE=MyISAM;

CREATE TABLE IF NOT EXISTS `gf_film` (
  `film_id` int(20) NOT NULL,
  `performed_by_actor_id` bigint(20) NOT NULL,
  KEY `film_id` (`film_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `gf_film_actor` (
  `film_id` int(20) NOT NULL,
  `actor_id` bigint(20) NOT NULL,
  KEY `film_actor_id` (`film_id`, `actor_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

现在您可以像这样创建查询:

SELECT a.*
  FROM `gf_film` AS f
  LEFT JOIN `gf_film_actor` AS fa ON f.`film_id` = fa.`film_id`
  LEFT JOIN `gf_actor` AS a ON fa.`actor_id` = a.`actor_id`
 WHERE f.`performed_by_actor_id` = 1
 LIMIT 0, 5;