从所有表中选择行的简便方法 [英] easy ways to select rows from all table
问题描述
我想在我的mysql数据库中选择一些行,我有3个具有相同结构的表,我尝试使用我创建的脚本并且此方法有效,但是似乎我的脚本中的行太多了. /p>
i want to select some rows in my mysql databases, I have 3 tables with the same structure, I have tried using the script that I created and this works, but it seems like it takes too many lines in my script.
<?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";
}
?>
还有另一种方法可以缩短我的脚本吗?谢谢:)
is there another way to shorten my script above ? thank you :)
推荐答案
如果所有表都具有相同的结构,则可以使用UNION
查询一次返回所有三个表中的行:
If all the tables have the same structure, you can use a UNION
query to return rows from all three tables at once:
$check = mysqli_query($con, "SELECT * FROM text WHERE keyword='$string'
UNION
SELECT * FROM sticker WHERE keyword='$string'
UNION
SELECT * FROM image WHERE keyword='$string'");
这将为您提供与三个现有查询相同的行集.请注意,将无法确定给定行来自哪个表,因此您可能需要添加一个额外的字段来表示该行,例如
This will give you the equivalent set of rows that your three existing queries give you. Note that there will be no way to determine which table a given row came from, so you may want to add an extra field to indicate that e.g.
$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'");
这篇关于从所有表中选择行的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!