【问题标题】:grab associated options from another table and merge with current results从另一个表中获取相关选项并与当前结果合并
【发布时间】:2011-10-01 11:09:06
【问题描述】:

我有 3 张桌子

  • 网站:ID、名称
  • 关联:类型、type_id、site_id
  • 选项:ID、姓名

我想要一个查询来选择 * 站点,然后从 assoc 中选择相关选项并从选项表中获取名称。

我想将代码缩短为一个查询:

     $getsites = mysql_query("SELECT * FROM sites")or die(mysql_error());
     while($row = mysql_fetch_array($getsites)){
     echo $row['name'];
     $getassoc = mysql_query("SELECT * FROM assoc WHERE type='options' AND site_id = '$row[ID]'")or die(mysql_error());
      echo'<ul>';
      while($subrow = mysql_fetch_array($getassoc)){
      $getoption = mysql_query("SELECT * FROM options WHERE ID = '$subrow[assoc_id]'")or die(mysql_error());
      $option = mysql_fetch_assoc($getoption);
      echo '<li>'.$option['name'].'</li>';
   }
   echo'</ul><br/>';

   }

【问题讨论】:

标签: php mysql sql join


【解决方案1】:

这称为连接:

select options.name
from sites
inner join assoc on sites.id = assoc.site_id
inner join options on options.id = assoc.assoc_id
where assoc.type = 'options'

问题:assoc表中没有assoc_id

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多