大家好,我有两张桌子

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可能有问题。

最佳答案

尝试这样的事情

$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。

关于php - PHP从两个表中选择不正常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23696171/

10-11 01:57