gpt4 book ai didi

php - 从两个表中选择并按时间戳排序

转载 作者:行者123 更新时间:2023-11-29 01:43:19 25 4
gpt4 key购买 nike

我有两个表(故事和状态),每个表都有这些公共(public)字段

id (unsigned int - auto increment)
creator (unsigned int)
message (varchar)
timestamp (unsigned int)

当我在网页上显示这些表时,我想使用一个查询按时间戳顺序从两个表中进行选择,但显示方式不同。

喜欢(按时间戳顺序):

SELECT * FROM `stories`, `statuses` WHERE `creator` = 1 ORDER BY `timestamp` DESC LIMIT 0, 10

Row 1: id, creator, message, timestamp, type ("status")
Row 2: id, creator, message, timestamp, type ("story")
Row 3: id, creator, message, timestamp, type ("status")
Row 4: id, creator, message, timestamp, type ("status")
Row 5: etc...

我需要类型字段在我的网页上以不同方式显示每一行。这只是每个表的简单形式;它们实际上要复杂得多,但我可以将这里的答案转移到我当前的查询中。

谢谢!

最佳答案

您可以使用UNION 运算符来组合两个或多个 SELECT 语句的结果集。

SELECT a.id, a.creator, a.message, a.timestamp, 'story' as table_type
FROM stories a
UNION
SELECT b.id, b.creator, b.message, b.timestamp, 'status' as table_type
FROM statuses b
WHERE ( a.creator = 1 ) OR (b.creator = 1)
ORDER BY 'timestamp' DESC LIMIT 0, 10;

请注意,默认情况下 UNION 运算符仅选择不同的值。要允许重复值,请使用 UNION ALL

SELECT a.id, a.creator, a.message, a.timestamp, 'story' as table_type
FROM stories a
UNION ALL
SELECT b.id, b.creator, b.message, b.timestamp, 'status' as table_type
FROM statuses b
WHERE ( a.creator = 1 ) OR (b.creator = 1)
ORDER BY 'timestamp' DESC LIMIT 0, 10;

希望对您有所帮助。

关于php - 从两个表中选择并按时间戳排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com