开发者

Matching IDs in two different tables

开发者 https://www.devze.com 2023-02-03 18:47 出处:网络
I have two tables; NEWS and CATEGORIES. In the NEWS table, there is CatID field which matches with CatID table in the categories. I get the categoryID with the following code but I want to the categor

I have two tables; NEWS and CATEGORIES. In the NEWS table, there is CatID field which matches with CatID table in the categories. I get the categoryID with the following code but I want to the category name of the news, not the ID. How can I pull it from the categories table?

<?开发者_JAVA技巧php 

 $SQL =  mysql_query("SELECT * FROM News WHERE Active = 1 ORDER BY DateEntered DESC");

   while ( $Result = mysql_fetch_array($SQL)) {
 $CatID[] = $Result[CatID];
 $NewsName[] = $Result[NewsName];
 $NewsShortDesc[] = $Result[NewsShortDesc];
 }
?>

                <div class="toparticle">
                    <span class="section"><?=$CatID[0] ?> </span>
                    <span class="headline"><?=$NewsName[0] ?></span>
                    <p><?=$NewsShortDesc[0] ?></p>
                </div>


You can change your SQL query to include an inner join to get the name. To illustrate, I'm going to make the assumption that the category name column in the 'CATEGORIES' table is called 'CatName.' You can use this query:

SELECT n.*, c.CatName FROM News n
INNER JOIN Categories c ON n.CatID = c.CatID
WHERE Active = 1
ORDER BY DateEntered ASC


By what I've understood, maybe you want to do:

SELECT name FROM CATEGORIES as c, NEWS as n WHERE c.CatID = n.CatID AND n.CatID = 123

I'm a bit rusty in SQL, I think it's something like this.

From what I've understood from your question, you want to do something like this.


In the following I create 2 table for news and categories :

Table News

id| cat_id | title

1 | 1 | Test

Table Categories

id | name

1 | Horror

u can select name of category use OUTER JOIN like this

SELECT news.*, categories.name AS category_name FROM news 
LEFT JOIN categories ON categories.id= news.cat_id;

if u want to know more about this outer join

0

精彩评论

暂无评论...
验证码 换一张
取 消