MYSQL从另一个与第一个表关联的表中获取名称

时间:2012-06-24 21:12:16

标签: php mysql

我无法弄清楚为什么这句话不起作用

$sql2 = mysql_query("
  SELECT myChurches.id AS id, myChurches.church_name AS church_name 
  FROM myChurches 
  INNER JOIN church_staff 
  ON church_staff.church_id=myChurches.id
  WHERE church_staff.mem_id='$logOptions_id' 
  ORDER BY myChurches.church_name 
  ASC
")

if(mysql_num_rows($sql2) > 0){
    while($row2 = mysql_fetch_array($sql)){
      $church_id = $row2['id']; 
      $church_name = $row2['church_name'];
        $options .= '<option value="'.$church_id.'">'.$church_name.'</option>';
    }
}

基本上我需要从一张桌子上找到一个教会工作人员的人,并希望从'myChurches'表中获得该教会的“名字”。希望这是有道理的。提前致谢

修改

表1具有唯一的id和church_name

表2具有唯一ID,church_id和mem_id

2 个答案:

答案 0 :(得分:0)

  SELECT id, church_name 
  FROM myChurches 
  WHERE id = (SELECT church_id FROM church_staff WHERE mem_id = '$logOptions_id')

编辑:这假设mem_id 如你所说的那样唯一 church_id不应该是唯一的,除非你做错了(因为它是外键)

答案 1 :(得分:0)

问题出在fetch数组中......变量与实际的查询变量不同。谢谢你的帮助