mysql连接2表结果

时间:2011-07-08 16:35:55

标签: mysql sql join

我有3张桌子:

网站:ID,名称
Assoc:site_id,assoc_type,assoc_id
选项:ID,名称

我想在一个

中执行以下查询
SELECT * FROM sites
    FOREACH site SELECT * FROM assoc WHERE assoc_type='option' AND site_id = site.ID
    FOREACH assoc SELECT name FROM options WHERE ID = assoc.ID

FOREACH SITE
    echo name, array(option 1, option2, option3);

这可能吗?

代码我试图缩短

      $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/>';

       }

1 个答案:

答案 0 :(得分:1)

SELECT s.name
     , ( SELECT o.name
         FROM Options AS o
           JOIN Assoc AS a
             ON a.assoc_id = o.ID
         WHERE a.site_id = s.id
           AND a.assoc_type='option'
         ORDER BY o.id
         LIMIT 1 OFFSET 0
       ) AS option1
     , ( SELECT o.name
         FROM Options AS o
           JOIN Assoc AS a
             ON a.assoc_id = o.ID
         WHERE a.site_id = s.id
           AND a.assoc_type='option'
         ORDER BY o.id
         LIMIT 1 OFFSET 1
       ) AS option2
     , ( SELECT o.name
         FROM Options AS o
           JOIN Assoc AS a
             ON a.assoc_id = o.ID
         WHERE a.site_id = s.id
           AND a.assoc_type='option'
         ORDER BY o.id
         LIMIT 1 OFFSET 2
       ) AS option3
FROM Sites AS s

如果您想要执行3个表的常规联接,要查找所有站点和相关选项,您可以使用:

SELECT s.name AS site
     , o.name AS option
FROM Sites AS s
    JOIN Assoc AS a
        ON a.site_id = s.id
    JOIN Options AS o
        ON o.ID = a.assoc_id
WHERE a.assoc_type = 'option'
ORDER BY s.name
       , o.name