Php从两个表中选择不正常

时间:2014-05-16 13:22:26

标签: php mysql select join

大家好我有两张桌子

seo_settings

| cat_id | cat_fullname | 
| 971    | catname 1    |
| 443    | catname 2    |

jcategories_to_hcategories

| jcategory_id | hcategory_id |
| 1            | 971          |
| 2            | 443          |
| 3            | 443          |

我希望按类别ID

获取cat_fullname

我正在使用此

$catIds = array(1,2,3)

foreach($catIds as $catId)
{
$sql3 = mysql_query("SELECT a.cat_fullname FROM seo_settings a, jcategories_to_hcategories b  WHERE a.cat_id = b.hcategory_id AND b.jcategory_id = $catId ");
    $data3 = mysql_fetch_array($sql3);
}

但$ data3返回booleanfalse

重要事项有行并且它们连接正确我假设我的sql中可能存在问题。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

$catIds = array(1,2,3);

$query = "
SELECT a.cat_fullname 
FROM seo_settings AS a 
LEFT JOIN jcategories_to_hcategories AS b ON jcategories_to_hcategories b 
WHERE b.jcategory_id IN (".implode(",", $catIds).")
";
$sql3 = mysql_query($query) or die(mysql_error());
while($data3 = mysql_fetch_assoc($sql3))
{
    echo $data3['cat_fullname'].'<br>';
}

旁注:停止使用mysql_并切换到mysqli_或PDO。

答案 1 :(得分:0)

您需要使用内部联接,而不是使用“,”列出两个表。您的查询应如下所示:

SELECT a.cat_fullname
FROM seo_settings a
INNER JOIN jcategories_to_hcategories b
    WHERE a.cat_id = b.hcategory_id
    AND b.jcategory_id = $catId