简体   繁体   中英

How to combine two Post/Category tables MYSQL SELECT queries into one

I have two MySQL queries:

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

First query selects posts and then second select the Path of the category by post_category please note that post_category will be taken from first query means post_category is common in both table.. in first table it is named as post_category and in second it is cat_ID

Right now I am running it in foreach loop which is not good. Also one thing to be noticed that second query will also return Array and that one array should correspond to post_category

Can any SQL expert help me?

Many Thanx

Please try this it might be helpful to you.

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

I would use LEFT JOIN

Like this:

$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";

You may need to tweak the WHERE clause to suite your needs more..

Please Note: This is one string, i have just split them onto two lines so it is easier to read. .= is to append the current string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM