Reputation: 297
i have built small forum script
in my index page i am using
$query = mysql_query("SELECT * FROM threads");
while($threads = mysql_fetch_array($query)){
echo 'Thread title ' . $threads['thread_title'];
echo '<br />Thread content ' . $threads['thread'];
}
to print the full site posts!
Now i want display the post category and post tags under the title
How i can get the categories and tags of post ?
i have table contain this information
table name -> relations
columns
post_id|category_name
i want join this table and get the category_name of each post!
so what is the right query?
NOTE: my site database is big .. so i want the speedy query
thank you very much
Upvotes: 0
Views: 322
Reputation: 1564
You should post the list of tables and fields they contain for the data that you want to see.
But the general idea should be something like this (assuming threads table has a foreign key on post_id to relations table's post_id):
SELECT t.*, r.category_name FROM threads as t
INNER JOIN relations as r on t.thread_id = r.thread_id
Just updated the above query based on the fields you just listed.
FYI: if you are concerned about performance, you should do the join of the data in your database query as shown above, executing additional queries for each row in your initial dataset will generate additional calls * number of threads. Now multiple that by the number of users viewing that page and the load on the database grows exponentially, and unnecessarily. All that can be done in one database query so that each user will only trigger one query in the database as opposed to hundreds or thousands potentially per view of the page.
Ok, in that case try something like this:
SELECT t.*, GROUP_CONCAT(r.category_name ORDER BY r.category_name SEPARATOR " ") as category_name
FROM threads as t
INNER JOIN relations as r on t.thread_id = r.thread_id
GROUP BY r.thread_id;
Upvotes: 1