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

时间:2012-12-10 00:47:59

标签: php mysql sql

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用 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;

我希望这可以帮到你。

答案 1 :(得分:0)

您可以使用JOINSELECT column AS 'some name'语法结合使用。

例如......

SELECT statuses.somefield AS 'some name' FROM `stories` JOIN(`statuses`) ON (status.id = stories.id) WHERE stories.creator = 1 ORDER BY stories.timestamp DESC LIMIT 0, 10