用于从不同表收集条目的 SQL 查询 - 需要 UNION 的替代方案
我正在运行 SQL 查询以从多个表中获取基本详细信息。按上次更新日期字段排序。它非常棘手,我在想是否有替代方法来使用 UNION 子句......我正在 PHP MYSQL 中工作。
实际上,我有几个包含新闻、文章、照片、事件等的表,需要在一个查询中收集所有这些表以显示一个简单的内容 - 网站上新添加的内容。
I'm running a sql query to get basic details from a number of tables. Sorted by the last update date field. Its terribly tricky and I'm thinking if there is an alternate to using the UNION clause instead...I'm working in PHP MYSQL.
Actually I have a few tables containing news, articles, photos, events etc and need to collect all of them in one query to show a simple - whats newly added on the website kind of thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许用 PHP 而不是 MySQL 来实现 - 如果您想要最新的
n
项,则获取每个新闻项、文章、照片和事件的最新n
项,然后在 PHP 中排序(显然,您需要每个的最后一个n
,然后您将在 PHP 中修剪数据集)。这可能比将它们与UNION
组合起来更容易,因为它们可能有很多不同的数据项。我不知道
UNION
的替代方案可以满足您的要求,希望这些获取不会太昂贵。不过,对此进行分析绝对是明智的。Maybe do it in PHP rather than MySQL - if you want the latest
n
items, then fetch the latestn
of each of your news items, articles, photos and events, and sort in PHP (you'll need the lastn
of each obviously, and you'll then trim the dataset in PHP). This is probably easier than combining those withUNION
given they're likely to have lots of data items which are different.I'm not aware of an alternative to
UNION
that does what you want, and hopefully those fetches won't be too expensive. It would definitely be wise to profile this though.如果您在查询中使用Join,您可以从与外键相关的不同表中选择数据。
If you use Join in your query you can select datas from differents tables who are related with foreign keys.
您可以从另一个角度来看:您需要绝对更新的信息吗? (当有人输入新信息时,它应该出现)
如果没有,您可以有一个表以您需要的格式保存查询结果(用作缓存),并每 5 分钟左右更新该表。然后您的查询问题就变得微不足道,因为您可以将更新作为多个更新在后台运行。
You can look of this from another angle: do you need absolutely updated information? (the moment someone enters new information it should appear)
If not, you can have a table holding the results of the query in the format you need (serving as cache), and update this table every 5 minutes or so. Then your query problem becomes trivial, as you can have the updates run as several updates in the background.