简体   繁体   English

内部联接查询帮助(获取帖子类别)

[英]help in inner join query (get post categories)

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 post_id |类别名称

i want join this table and get the category_name of each post! 我想加入此表并获取每个帖子的category_name!

so what is the right query? 那么什么是正确的查询?

NOTE: my site database is big .. so i want the speedy query 注意:我的站点数据库很大..所以我要快速查询

thank you very much 非常感谢你

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): 但是一般的想法应该是这样的(假设线程表在post_id上有一个外键到关系表的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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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