php – 为WHERE条件选择相等数量的记录

我有一个数据库,其中有超过一百万条记录.我希望从3个不同条件的数据库中获得相同数量的记录.我目前正在使用执行3个MySQL查询代码.我想知道是否有可能使用一个SELECT查询获得相同的结果?

以下代码为每个站点= X条件选择相等数量的20条记录.

<?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.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...