从数据库重复数据?

zlhcx6iw  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(352)

包含以下列的数据库:

我用我的程序假装用户选择了他们想要的标签,这样屏幕上就会显示与所选标签相对应的练习。例如,如果用户选择标签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>";
}
mgdq6dx1

mgdq6dx11#

您的查询有问题,请尝试添加 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>";
}
7kjnsjlb

7kjnsjlb2#

我建议你尝试使用分组表达法,比如:

$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>";
}

相关问题