2

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

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

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

谢谢!

4

2 回答 2

5

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

我希望这可以帮助你。

于 2012-12-10T04:02:40.300 回答
0

您可以JOIN结合SELECT column AS 'some name'语法使用 a 来执行此操作。

例如...

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
于 2012-12-10T00:54:52.597 回答