【发布时间】:2011-02-06 17:34:51
【问题描述】:
在我的索引文件中,我使用这个函数(在另一个文件中)从数据库中获取数据:
function get_all_threads($link, $start)
{
$threads = select_Query("SELECT thread.title, thread.id as t_id,
thread.content, author.username, author.id as a_id,
GROUP_CONCAT(DISTINCT tags.name ORDER BY tags.name DESC SEPARATOR ',') AS tags
FROM thread JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tags ON thread_tags.tag_id = tags.id
INNER JOIN author on author.id = thread.author_id
GROUP BY thread.id DESC
LIMIT $start, 30", $link);
return $threads;
}
我的索引文件中的代码如下:
$threads = get_all_threads($link, $start);
include FORUM_ROOT . 'html/main/threads.html.php';
在threads.html.php中
<?php foreach ($threads as $thread): ?>
<h1><?php echo $thread['title']; ?></h1>
<?php echo $thread['content']; ?>
<?php echo $thread['tags']; ?> <!-- All of these appear as one -->
<?php endforeach; ?>
如您所见,我得到了线程、它们的作者和它们的标签。但是我使用 GROUP_CONCAT 作为标签,所以当我想让每个单独的标签成为一个链接时,比如在threads.html.php中:
<a href="?tag=<?php echo $thread['tags']; ?>" >
<?php echo $thread['tags']; ?>
</a>
所有标签都显示为一个链接,(例如,如果标签是苹果、橙子、香蕉,它们将显示为apple, orange, banana 而不是apple、orange、banana):
我知道要拆分这些标签,我可以使用explode然后迭代每个标签,如下所示:
<?php $tags = array();
$tags = explode(',', $thread['tags']);
?>
(Tagged:
<?php foreach ($tags as $tag): ?>
<a href="/tag?=<?php echo $tag;?>"><?php echo $tag; ?></a>
<?php endforeach; ?>)
但是,我必须在threads.html.php 中执行此操作,并且我想保持演示代码分开。
在 index.php 中有更简洁的方法吗?此外,对于超过 30 个线程,迭代每个线程并分解每个标签将花费太长时间。
编辑:
我的表结构如下:
thread、author_threads、author、tag、thread_tags、reply 和 author_replies
1:http://apple,橙子,香蕉
【问题讨论】:
-
你能添加你的数据库表结构吗
-
如果可能的话,我更愿意简化问题。
-
我不认为
GROUP_CONCAT是 SQL 标准……您使用哪个 DBS? -
你为什么首先使用 group_concat?我看到您使用很多连接来获取线程的标签……哦,我想我现在明白了。您有一个可能带有多个标签的线程,并且在打印标签时要链接它们!?这很简单:不要在 1 个查询中执行此操作。在一个查询中获取线程,然后在另一个查询中获取线程的标签。
-
@Kissaki GROUP_CONCAT 是 MySQL 函数。