我有两个表(故事和状态),每个表都有这些公共字段
id (unsigned int - auto increment)
creator (unsigned int)
message (varchar)
timestamp (unsigned int)
Run Code Online (Sandbox Code Playgroud)
当我在网页上显示这些表时,我想使用一个查询按时间戳顺序从两个表中进行选择,但以不同的方式显示它们。
喜欢(按时间戳顺序):
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...
Run Code Online (Sandbox Code Playgroud)
我需要 type 字段在我的网页上以不同的方式显示每一行。而这只是每张表的简单形式;它们实际上要复杂得多,但我可以将答案从这里转移到我当前的查询中。
谢谢!
您可以使用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;
Run Code Online (Sandbox Code Playgroud)
请注意,默认情况下 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;
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助你。