douye9822 2012-12-10 00:47
浏览 316
已采纳

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

I have two tables (stories and status), each with these common fields

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

When I display these tables on my webpage, I want to use one query to select from both tables in order of timestamp, but display them differently.

Like (in order of timestamp):

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

I need the type field to display each row differently on my webpage. And this is only the simple form of each table; they are actually much more complex, but I could transfer the answer from here over to my current query.

Thanks!

  • 写回答

2条回答 默认 最新

  • doushiposong30622 2012-12-10 04:02
    关注

    You can use UNION operator to combine the result-set of two or more SELECT statements.

    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;
    

    Please note that the UNION operator selects only distinct values by default. To allow duplicate values, use 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;
    

    I hope this could help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染