尝试在几个表上形成SQL连接

时间:2013-12-10 21:21:55

标签: php mysql sql join

所以我试图弄清楚如何使用1个查询来做到这一点。以下是我对几个查询的看法

$file_url = 'http://'.$cms.'/filemanager/gallery';
$link_url = '/our-process/gallery/';
include 'inc/config.php';
function gallerySafeName($var){
    $var = strtolower(preg_replace('([^a-zA-Z0-9_])','-',$var));
    return $var;
}
$galleryimages = array();
$sql = "SELECT * FROM `cms_gallery_categories` ORDER BY RAND() LIMIT 3";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)){
    $sql1 = "SELECT * FROM `cms_gallery_images` WHERE `image_id` = ".$row['category_image_id'];
    $result1 = mysqli_query($con,$sql1);
    while ($row1 = mysqli_fetch_array($result1)){
        $sql2 = "SELECT * FROM `cms_gallery` WHERE `gallery_id` = ".$row1['gallery_id'];
        $result2 = mysqli_query($con,$sql2);
        while ($row2 = mysqli_fetch_array($result2)){
            print '<li>
            <a href="'.$link_url.$row['category_name'].'/'.$row2['gallery_name'].'/'.gallerySafeName($row1['image_caption']).'/">
            <img  width="210" height="133" border="0" src="'.$file_url.'/'.$row['category_name'].'/'.$row2['gallery_name'].'/'.$row1['image_name'].'" />
            </a>
            </li>';
        }
    }
}

我试图从图库类别中获取3个随机条目,并分配图像来表示该类别。然后获取图库名称,然后获取图像名称以形成img src和链接。我的表结构如下

-cms_gallery_categories
category_id
category_title
category_name
category_image_id

-cms_gallery
gallery_id
gallery_title
gallery_name
category_id

-cms_gallery_images
image_id
image_name
image_caption
gallery_id

图片属于图库,图库属于类别

1 个答案:

答案 0 :(得分:1)

SELECT GC.*, G.*, I.*
FROM cms_gallery_categories GC
INNER JOIN cms_galleries G ON (G.category_id = GC.category_id)
INNER JOIN cms_gallery_images I ON (I.gallery_id = G.gallery_id)
ORDER BY RAND() LIMIT 3

您需要将字段限制为仅需要的字段。从我在你的代码中看到的,就是这样:

SELECT GC.category_name, G.gallery_name, I.image_caption FROM...
  

更多信息