具有以下列的数据库:
我假装我的程序是用户选择他们想要的标签,以便与所选标签相对应的练习显示在屏幕上。例如,如果用户选择标签1,则会出现练习1和2。如果选择标签1和3,则会出现练习1和2。
我的程序的问题是,例如,当用户选择标签1和3时,练习1和2出现,但重复2次。或者,当您选择标签1和2时,重复练习1。
有人知道吗,这样就不会发生?只显示一次练习?
在这里显示部分代码:
$sql = "SELECT * FROM exercises, union, tags where exercise_id = exercise_id_fk and tag_id = tag_id_fk";
if (!empty($_SESSION['tags_array'])) {
$sql .= " and (";
foreach ($_SESSION['tags_array'] as $tagId)
$sql .= 'tag_id = ' . $tagId . ' or ';
$sql .= "tag_id = -1);";
}
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["exercise_id"] . ". " . $row["title"] . "<br>";
}
答案 0 :(得分:0)
我建议您尝试使用GROUP BY表达式进行尝试,例如:
$sql = "SELECT * FROM exercises e INNER JOIN union u ON u.exercise_id_fk = e.exercise_id INNER JOIN tags t ON t.tag_id = u.tag_id_fk WHERE 1 = 1";
if (!empty($_SESSION['tags_array'])) {
$sql .= " and (";
foreach ($_SESSION['tags_array'] as $tagId)
$sql .= 't.tag_id = ' . $tagId . ' or ';
$sql .= "t.tag_id = -1)";
}
$sql .= " GROUP BY e.exercise_id;";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["exercise_id"] . ". " . $row["title"] . "<br>";
}
答案 1 :(得分:-1)
问题与查询有关,请最后尝试在查询中添加group by exercise_id_fk
。
$sql = "SELECT * FROM exercises, union, tags where exercise_id = exercise_id_fk and tag_id = tag_id_fk";
if (!empty($_SESSION['tags_array'])) {
$sql .= " and (";
foreach ($_SESSION['tags_array'] as $tagId)
$sql .= 'tag_id = ' . $tagId . ' or ';
$sql .= "tag_id = -1)";
}
$sql .= ' group by exercise_id_fk';
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["exercise_id"] . ". " . $row["title"] . "<br>";
}