【问题标题】:How I can select from two different table but order with time [closed]我如何从两个不同的表中进行选择但随时间排序[关闭]
【发布时间】:2014-03-25 12:56:36
【问题描述】:

我有两个不同的表,分别命名为“groupposts”和“posts” 在这些表中有这些列 我的意思是“时间”列的名称在两者中都不同! 我需要使用 UNION 来选择这些表

表 GROUPPOSTS

    ID      Gpost      Gtime
    ________________________
    1       Test       3

表帖

    ID      Ppost      Ptime
    ________________________
    1       Test       1

我想从两者中选择,但按 Gtime 和 PTime desc 排序
告诉我如何获得它以及如何向他们展示 我的意思是我如何显示“ppost”如果“ptime”会更快选择,或者“gpost”会怎样?

谢谢

【问题讨论】:

  • 如果没有排序,你是如何从中选择的?
  • 亲爱的@Anthony Grist,我想按时间列排序,但这些表中时间列的名称不同
  • 这不是我问你的。我知道你想做什么,我要求你发布你已经从你的两个表中选择的 SQL 查询而不用担心顺序。是加盟吗?是工会吗?
  • 我需要为两个不同的表使用 Union

标签: php html mysql sql select


【解决方案1】:

应该这样做:

(SELECT Gpost AS post, Gtime AS time FROM GROUPPOSTS)
UNION
(SELECT Ppost AS post, Ptime AS time FROM POSTS)
ORDER BY time

【讨论】:

    【解决方案2】:

    您只需要在 union all 子句的最后一个 SQL 部分中包含 order by 语句。 整个组合结果集将按该列排序。

      select id, gpost, gtime as xtime from GROUPPOSTS
      union all
      select id, ppost, ptime as xtime from POSTS
      ORDER BY ptime
    

    【讨论】:

      【解决方案3】:

      你在找这个吗?

      select *
      from
      (
        select id, gpost, gtime as xtime from GROUPPOSTS
        union all
        select id, ppost, ptime as xtime from POSTS
      )
      order by xtime;
      

      编辑:哎呀,上面的陈述对于所要求的内容来说太复杂了。 ORDER BY 子句适用于完整的查询,列名取自第一个查询(在 UNION ALL 之前)。所以这就足够了:

      select id, gpost, gtime from GROUPPOSTS
      union all
      select id, ppost, ptime from POSTS
      order by gtime;
      

      当然,我们仍然可以为该列使用别名。这是个人喜好问题。

      【讨论】:

      • 是的,我知道我必须做的了,谢谢
      猜你喜欢
      • 2020-06-18
      • 2022-01-24
      • 2020-09-23
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多