可能重复:
How to combine two Post/Category tables MYSQL SELECT queries into one
我有两个MYSQL查询:
1) "SELECT ID,post_title,post_category,post_perma FROM ".TBL_POSTS."
WHERE published='1' AND page='0' ORDER BY ID ASC LIMIT 50"
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
我这样用:
$sql="SELECT ID, post_title, post_category,post_perma
FROM ".TBL_POSTS."
WHERE published='1'
AND page='0'
ORDER BY ID ASC LIMIT 50";
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result)){
$sql2="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='".$row['post_category']."'
ORDER BY p.lft";
$result2=mysql_query($sql2);
while($row2=mysql_fetch_assoc($result2)){
$path.='/'.$row2['cat_nicename'];
}
$link.='<a href="'.$path.'">'.$row['post_title'].'</a><br>';
$path='';
}
echo($link);
exit;
}
这就是我在链接中获取路径的方式..现在我想要的是:
我想结合两个查询,以便我没有在while循环中运行第二个查询。 它变得非常糟糕,因为如果我收到100个帖子..第二个查询将运行100次以获取路径。
答案 0 :(得分:1)
您可以JOIN
这两个表格如下:
SELECT
p.ID,
p.post_title,
c.cat_nicename,
p.post_perma
FROM TBL_POSTS p
INNER JOIN TBL_CATEGORIES c
ON p.CategoryID = c.Cat_ID
WHERE p.published = '1'
AND p.page = '0'
ORDER BY p.ID ASC
LIMIT 50
答案 1 :(得分:0)
您可以使用UNION将所有这些组合成一个查询。
真的,你需要做这样的事情,这样所有的列都不会相互结合。此外,两个select语句都需要选择相同数量的列。
编辑:此外,在MySQL UNION中你只能有1个订单,它必须在最后一个SELECT中,所以你必须相应地调整你的查询。
(SELECT ID,
post_title,
post_category,
post_perma,
NULL AS cat_id,
NULL AS cat_nicename
FROM ".TBL_POSTS."
WHERE published='1'
AND page='0')
ORDER BY ID ASC LIMIT 50
UNION
(SELECT
NULL AS ID,
NULL AS post_title,
NULL AS post_category,
NULL AS post_perma,
p.cat_ID,
p.cat_nicename
FROM ".TBL_CATEGORIES." n,
".TBL_CATEGORIES." p
WHERE n.cat_ID='".post_category."'
AND n.lft BETWEEN p.lft AND p.rgt)
ORDER BY p.lft
答案 2 :(得分:0)