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

Php 从两个表中选择并按时间戳排序,php,mysql,sql,Php,Mysql,Sql,我有两个表(故事和状态),每个表都有这些公共字段 id (unsigned int - auto increment) creator (unsigned int) message (varchar) timestamp (unsigned int) 当我在我的网页上显示这些表时,我想使用一个查询从两个表中按时间戳的顺序进行选择,但显示方式不同 类似(按时间戳的顺序): 我需要类型字段在我的网页上以不同的方式显示每一行。这只是每个表的简单形式;它们实际上要复杂得多,但我可以将答案从这里转移到我

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

id (unsigned int - auto increment)
creator (unsigned int)
message (varchar)
timestamp (unsigned int)
当我在我的网页上显示这些表时,我想使用一个查询从两个表中按时间戳的顺序进行选择,但显示方式不同

类似(按时间戳的顺序):

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


谢谢

您可以使用
JOIN
结合
选择列作为“某个名称”
语法来执行此操作

例如


可以使用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运算符仅选择不同的值。要允许重复值,请使用“全部联合”

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;

我希望这能对您有所帮助。

naoki关于使用并集的答案是可行的,因为您将来自两个结构相似的不同表的数据组合在一起。太好了!谢谢你的帮助:)
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;
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;