我有两个MySQL查询:
1) "SELECT ID,post_title,post_category,post_perma FROM ".TBL_POSTS."
WHERE published='1' AND page='0' ORDER BY ID DESC LIMIT 10"
2) "SELECT p.cat_ID,p.cat_nicename FROM ".TBL_CATEGORIES." n, ".TBL_CATEGORIES." p
WHERE n.lft BETWEEN p.lft AND p.rgt AND n.cat_ID='".post_category."' ORDER BY p.lft
第一个查询选择帖子,然后第二个按post_category
选择类别的路径请注意post_category
将从第一个查询中获取post_category
在两个表中都很常见...第一个表名为post_category
,第二个表名为cat_ID
现在我在foreach循环中运行它并不好。还有一件事需要注意,第二个查询也将返回Array,并且一个数组应该对应post_category
任何SQL专家都可以帮助我吗?
Many Thanx
答案 0 :(得分:4)
请尝试这可能对您有帮助。
SELECT a.ID, a.post_title,a.post_category,a.post_perma, b.cat_ID, b.cat_nickname
FROM (SELECT ID,post_title,post_category,post_perma FROM ".TBL_POSTS." WHERE published='1' AND page='0' ORDER BY ID DESC LIMIT 10) a
LEFT JOIN (SELECT p.cat_ID as cat_ID,p.cat_nicename as cat_nickname FROM " . TBL_CATEGORIES . " n, " . TBL_CATEGORIES . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n.cat_ID = '" .$post_category. "' ORDER BY p.lft) b ON a.ID = b.cat_ID
答案 1 :(得分:0)
我会使用 LEFT JOIN
像这样:
$sql = "SELECT `p`.`ID`,`p`.`post_title`,`p`.`post_category`,`p`.`post_perma`,`c`.`cat_ID`,`c`.`cat_nicename` FROM `".TBL_POSTS."` AS `p` ";
$sql .= "LEFT JOIN `".TBL_CATEGORIES."` AS `c` ON `c`.`cat_ID`=`p`.`post_category` WHERE `p`.`published`='1' AND `p`.`page`='0' ORDER BY `p`.`ID` DESC LIMIT 10";
您可能需要调整WHERE
子句以满足您的需求..
请注意:这是一个字符串,我刚将它们分成两行,因此更容易阅读。 .=
将附加当前字符串。