我有一个数据库,其中有超过一百万条记录.我希望从3个不同条件的数据库中获得相同数量的记录.我目前正在使用执行3个MySQL查询的代码.我想知道是否有可能使用一个SELECT查询获得相同的结果?
<?PHP
/*---------*/
$db1 = MysqLi_query($connect, "SELECT * FROM news WHERE site='1' ORDER BY id DESC LIMIT 0,20");
$db2 = MysqLi_query($connect, "SELECT * FROM news WHERE site='2' ORDER BY id DESC LIMIT 0,20");
$db3 = MysqLi_query($connect, "SELECT * FROM news WHERE site='3' ORDER BY id DESC LIMIT 0,20");
/*------------*/
?>
解决方法:
您可以使用UNION ALL
组合多个Select查询的结果.我们需要确保在所有Select查询中返回的列数相同.
(SELECT * FROM news WHERE site='1' ORDER BY id DESC LIMIT 0,20)
UNION ALL
(SELECT * FROM news WHERE site='2' ORDER BY id DESC LIMIT 0,20)
UNION ALL
(SELECT * FROM news WHERE site='3' ORDER BY id DESC LIMIT 0,20)
现在,请记住UNION的结果始终是无序数据集.如果您希望最终结果按ID排序;您可以在最后添加明确的Order By.在Docs中进行了很好的讨论:
However, use of ORDER BY for individual SELECT statements implies
nothing about the order in which the rows appear in the final result
because UNION by default produces an unordered set of rows. Therefore,
the use of ORDER BY in this context is typically in conjunction with
LIMIT, so that it is used to determine the subset of the selected rows
to retrieve for the SELECT, even though it does not necessarily affect
the order of those rows in the final UNION result. If ORDER BY appears
without LIMIT in a SELECT, it is optimized away because it will have
no effect anyway.