我有一个数据库,其中有超过一百万条记录.我希望从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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。