从所有表中选择行的简便方法

时间:2019-05-05 03:46:00

标签: php mysql mysqli

我想在我的mysql数据库中选择一些行,我有3个具有相同结构的表,我尝试使用我创建的脚本并且此方法有效,但是似乎我的脚本中的行太多了。 / p>

<?php
$check1 = mysqli_query($con, "SELECT * FROM text WHERE keyword='$string'");
$check2 = mysqli_query($con, "SELECT * FROM sticker WHERE keyword='$string'");
$check3 = mysqli_query($con, "SELECT * FROM image WHERE keyword='$string'");
if(mysqli_num_rows($check1) == 0 && mysqli_num_rows($check2) == 0 && mysqli_num_rows($check3) == 0) {
    echo "success";
}
?>

还有另一种方法可以缩短我的脚本吗?谢谢:)

2 个答案:

答案 0 :(得分:0)

如果所有表都具有相同的结构,则可以使用UNION查询一次返回所有三个表中的行:

$check = mysqli_query($con, "SELECT * FROM text WHERE keyword='$string'
                             UNION
                             SELECT * FROM sticker WHERE keyword='$string'
                             UNION
                             SELECT * FROM image WHERE keyword='$string'");

这将为您提供与三个现有查询相同的行集。请注意,将无法确定给定行来自哪个表,因此您可能需要添加一个额外的字段来表示该行,例如

$check = mysqli_query($con, "SELECT *, 'text' AS src FROM text WHERE keyword='$string'
                             UNION
                             SELECT *, 'sticker' AS src FROM sticker WHERE keyword='$string'
                             UNION
                             SELECT *, 'image' AS src FROM image WHERE keyword='$string'");

答案 1 :(得分:0)

  1. 请确保您在所有3个表的关键字列上都具有索引,以便避免进行完整的表扫描。 在下面创建索引。
    CREATE INDEX keyword ON text (keyword);
    CREATE INDEX keyword ON sticker (keyword);
    CREATE INDEX keyword ON image (keyword);
  1. 如果您想知道3个表中是否有关键字,则仅选择 1行
    <?php
    $check = mysqli_query($con, "SELECT 1 FROM text WHERE keyword='$string' limit 1
                                UNION SELECT 1 FROM sticker WHERE keyword='$string' limit 1
                                UNION SELECT 1 FROM image WHERE keyword='$string' limit 1");
    if(mysqli_num_rows($check) == 0 ) {
        echo "success";
    }
    ?>

如果要从每个表中选择一些行,请使用限制。我仅以5为例。


    <?php
    $check1 = mysqli_query($con, "SELECT * FROM text WHERE keyword='$string' limit 5");
    $check2 = mysqli_query($con, "SELECT * FROM sticker WHERE keyword='$string' limit 5");
    $check3 = mysqli_query($con, "SELECT * FROM image WHERE keyword='$string' limit 5");
    if(mysqli_num_rows($check1) == 0 && mysqli_num_rows($check2) == 0 && mysqli_num_rows($check3) == 0) {
        echo "success";
    }
    ?>