我试图加入两张桌子。一个是类别,另一个是子类别。类别表中的id成为子类别表中的cat id
类别
id name catimage
2 cat1 image1
子类
id name subcatimage catid
1 subcat1 image2 2
代码是
<?php
ob_start();
require_once('config.php');
$selectsubcategory = mysql_query("SELECT category.name, subcategory.name, category.catimage, subcategory.id, subcategory.catid FROM category INNER JOIN subcategory ON category.id=subcategory.catid ");
$posts = array();
if(mysql_num_rows($selectsubcategory))
{
while($post = mysql_fetch_assoc($selectsubcategory))
{
$posts[] = $post;
}
header('Content-type: application/json');
echo stripslashes(json_encode(array('subcategorylist'=>$posts)));
}
else
{
header('Content-type: application/json');
echo stripslashes(json_encode(array('subcategorylist'=>'No subcategory')));
}
?>
我收到所有细节,但问题是我没有在结果中获得category.name。任何人都可以帮忙
P.S我已经使用了sql,现在稍后会更改它我的关注点是功能部分
答案 0 :(得分:2)
subcategory.name会覆盖您的类别名称。 您必须使用别名作为子类别名称:
$selectsubcategory = mysql_query("SELECT category.name, subcategory.name AS sub_name, category.catimage, subcategory.id, subcategory.catid FROM category INNER JOIN subcategory ON category.id=subcategory.catid ");
答案 1 :(得分:1)
这可能会对你有帮助......
此处 MainCatName 将显示类别名称字段数据...和 SubCatName 将显示为子类别名称字段数据...
SELECT
`category`.`name` AS MainCatName
, `subcategory`.`name` AS SubCatName
FROM
`category`
INNER JOIN `subcategory`
ON (`category`.`id` = `subcategory`.`catid`);
答案 2 :(得分:0)
SELECT
Category.name, category.catimage,
subcategory.name, subcategory.id,
subcategory.catid
FROM
category INNER JOIN subcategory
WHERE
category.id = subcategory.catid