如何在一个语句中使用两个mysql表

时间:2014-01-31 00:51:48

标签: php mysql

所以,我已经放入了一个最喜欢的图片表,我无法弄清楚如何让它正常工作

基本上,这是设置:

ImageFavs
FavID, UserID, ImgID

ImageList
ImgID, SiteID

我希望从收藏夹表格中选择20张左右的图片,但只能选择与图片列表中的siteid匹配的图片

这是我目前的代码,但我突然意识到它会从收藏夹中选择20张图片,然后只有在匹配的网站被实际检查时才会显示它们。

#select matching sites
for($i=0;$i<count($sites)-1;$i++){
    $siteinfo = explode("-",$sites[$i]);
    $siteid = $siteinfo[0];
    $sitegroup = $siteinfo[1];
    $selection[$siteid]="exists";
    if($i!=0){
        $sqlextra .= " OR ";
    }
    else{
        $sqlextra = "AND (";
    }
    $sqlextra .= "SiteID='".$siteid."'";
}
if(!empty($sqlextra)){
    $sqlextra .= ")";
}
else{
    $sqlextra = "AND SiteID='-1'";
}

#show favourites
if($_GET['f']==1){
    $sql="SELECT * FROM ImageFavs WHERE UserID='".$_SESSION['User_ID']."' AND Active = '1' ORDER BY RAND() LIMIT 20";
    #(rand is just me being lazy, eventually I'll figure out how to separate it onto pages)
    $result = mysql_query($sql);
    $num = mysql_numrows($result);
    if($num>0){
        while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
            if(empty($sqlextra2)){
                $sqlextra2 = " AND (";
            }
            else{
                $sqlextra2 .= " OR ";
            }
            $sqlextra2 .= "ImgID='".$row['ImgID']."'";
        }
        $sqlextra2 .= ")";
    }
}
#don't show favourites
if(empty($sqlextra2)){
    $sqlextra2 = " ORDER BY RAND() LIMIT 20";
}
$sql="SELECT * FROM ImageList WHERE Valid='1' ".$sqlextra.$sqlextra2;

这个输出$ sql看起来好像可以这么整洁,但它的一个例子是这样的

SELECT * FROM ImageList WHERE Valid='1' AND (SiteID='6') AND (ImgID='5634' OR ImgID='8229' OR ImgID='9093' OR ImgID='5727' OR ImgID='7361' OR ImgID='5607' OR ImgID='7131' OR ImgID='5785' OR ImgID='7339' OR ImgID='5849' OR ImgID='7312' OR ImgID='5641' OR ImgID='8921' OR ImgID='7516' OR ImgID='7284' OR ImgID='5873' OR ImgID='8905' OR ImgID='7349' OR ImgID='7392' OR ImgID='8725')

此外,虽然我在这里,是否会有非资源方式来计算每个网站的用户收藏数?

这不是什么大事,只是在个人网站上乱搞,看看我能做些什么。

3 个答案:

答案 0 :(得分:1)

你想使用“JOIN”

SELECT * FROM ImageFavs LEFT JOIN ImageList ON ImageFavs.ImgID = ImageList.ImgID WHERE ImageList.SiteID = <your_site_id>

答案 1 :(得分:1)

你可以INNER JOIN你的两张桌子来获得你想要的结果。当您需要来自两个表的结果时,将使用INNER。最好使用别名来保持你的表格。

SELECT l.*
FROM ImageFavs f
    INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE l.SiteID = [your site ID]
    AND f.UserID='" . $_SESSION['User_ID'] . "' 
    AND f.Active = '1' 
    ORDER BY RAND() LIMIT 20

要按网站计算,您可以使用GROUP BY。我认为这应该让你算上

SELECT COUNT(f.ImgID)
FROM ImageFavs f
    INNER JOIN ImageList l ON f.ImgID = l.ImgID
WHERE f.UserID='" . $_SESSION['User_ID'] . "' 
    AND f.Active = '1' 
GROUP BY l.SiteID

答案 2 :(得分:1)

这有效 -

//Assuming $site_id contains the site ID/
$query = "select *.IF from ImageFavs as IF, ImageList as IL where IL.ImgId = IF.ImgId and IL.SiteId = $site_id LIMIT 20"