我正在尝试为我的漫画网站实现一个标记系统。
目标与 SO 类似 - 用户可以单击多个标签,并且这些标签会保留在他们身边 - 主要区别是我使用 $_SESSION 来存储它们,而不是 SO 拥有的登录系统。
一旦用户点击标签,就会将显示的漫画限制为与标签 ID 匹配的漫画。建议我有 3 个单独的表 - 一张用于漫画,一张用于标签,以及一个关系表 ComicTags。一篇漫画可以有 0 个或多个标签,一个标签可以与 1 个或多个漫画关联。
我正在努力编写正确的 SQL 查询来将漫画 ID 与 0 个或多个标签 ID 连接起来。
我的 table 会这样设置吗?
我检索这些的查询会像这样吗?
$result = $mysqli->query("SELECT * FROM comics c INNER JOIN comictags ct ON (c.id = ct.comicID) WHERE ct.tagID IN (1, 2, 3) GROUP BY c.id");
谢谢!
编辑
我正确地理解了这一点吗?
1)首先选择漫画和标签中的所有列...
2) 将漫画 ID 加入 ComicTags 表中的匹配 ID
3) 将标签 ID 与 ComicTags 表中的匹配 ID 连接起来
4) 在这种情况下,仅选择那些标记 ID 为 1 或 2 的内容...这样将返回所有漫画 ID...
编辑2:代码
<?php
session_start();
include 'dbconnect.php';
$site = (isset($_GET['site']) ? ($_GET['site']) : "comics");
$tag = $_GET['_tagChoice'];
if (!isset($_SESSION['tags'])) {
$_SESSION['tags'] = array();
}
$tag = $mysqli->real_escape_string($tag);
$_SESSION['tags'][] = $tag;
foreach ($_SESSION['tags'] as $tag) {
echo $tag;
}
$_SESSION['tags'] = array_unique($_SESSION['tags']);
$result = $mysqli->query(
"SELECT c.*, t.*
FROM comics c
LEFT JOIN comictags ct ON (c.id = ct.comicID)
LEFT JOIN tags t ON (t.id = ct.tagID)
WHERE ct.tagname IN (" . implode(',', $_SESSION['tags']). ")
OR ct.tagname IS NULL");
mysqli_close($mysqli);
while ($row = $result->fetch_assoc()) {
echo $row['comic_id'];
}
//session_destroy();
?>
最佳答案
您需要通过将comicstags
表连接到tags
表,以获得TagName
。因此,再添加一个 INNER JOIN
:
SELECT
/* Selecting all columns from comics and tags, not from comicstags */
c.*,
t.*
FROM
comics c
/* First join matches comics to comicstags */
INNER JOIN comictags ct ON (c.id = ct.comicID)
/* Second join pairs comicstags to tags */
INNER JOIN tags t ON (t.TagID = ct.TagID)
WHERE
ct.tagID IN (1, 2, 3)
/* Or those which have no tags */
OR ct.tagID IS NULL
GROUP BY
已被删除,因为您没有使用聚合(COUNT()、SUM()、MIN()、MAX()
等)。如果您只需要唯一的行,请将 DISTINCT
添加到 SELECT
中。
关于PHP 标签系统 - SESSION 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069701/