SQL - 如何从两个表中按日期排序?

时间:2012-01-19 23:12:34

标签: sql date sql-order-by

我会试着清楚地问我的问题......

我有三个表,每个表都包含一个日期值。节点和产品具有“创建日期”,共享具有“时间戳”日期。我需要弄清楚如何按单一日期订购......我需要将两个日期合并在一起......

它需要适合这个陈述

SELECT sc.auto_id AS autoid, sc.uid AS sharedby, n.nid, sc.message AS sharedmessage, 
    (
SELECT COUNT(1) 
FROM {share_content} AS sc2
  WHERE sc2.nid = sc.nid
) AS countnid 
FROM {node} n LEFT JOIN {content_type_product} p on n.nid = p.nid 
  LEFT JOIN {share_content} sc on sc.auto_id=
(
SELECT MAX(auto_id) FROM share_content sc1
WHERE sc1.nid = n.nid 
LIMIT 1
) 
WHERE (
    n.type = 'blog' 
    OR n.type = 'field_school' 
    OR n.type = 'photo_gallery' 
    OR n.type = 'forum' 
    OR n.type = 'product_review' 
    OR n.type = 'product' and p.field_front_page_value = 'Add to feed'
    OR n.type = 'reference'
    OR n.type = 'video_gallery'
    OR n.type = 'video'   
    OR n.type = 'groups' 
    OR n.type = 'group_post'  
    OR n.type = 'status' 
    OR (n.type = 'event' AND n.uid != '2')
    OR n.type = 'jobs_careers'
    OR n.type = 'post_link'
    OR (n.type = 'news_article' AND n.uid != '2' AND n.uid != '0'))  
AND n.status = '1' 
ORDER BY n.created DESC";

(顺序需要是n.created,p.created和sc.date_shared之间的合并)...

谢谢,

马特

2 个答案:

答案 0 :(得分:0)

怕怕!!!

ORDER BY 
(CASE WHEN Table2.Id IS NULL AND Table3.Id IS NULL THEN Table1.Created_on
      WHEN Table2.Is IS NULL 
       THEN (CASE WHEN Table1.CreatedOn <= Table3.CreatedOn THEN Table1.CreatedOn 
                  ELSE Table3.CreatedOn END)
      WHEN Table3.Id IS NULL
       THEN (CASE WHEN Table1.CreatedOn <= Table2.timestamp THEN Table1.CreatedOn 
                  ELSE Table2.timestamp END)
      WHEN Table1.CreatedOn <= Table3.CreatedOn AND Table1.CreatedOn <= Table2.timestamp
       THEN Table1.CreatedOn
      WHEN Table3.CreatedOn <= Table1.CreatedOn AND Table3.CreatedOn <= Table2.timestamp
       THEN Table3.CreatedOn
      ELSE Table2.timestamp END)

答案 1 :(得分:0)

使用“SELECT AS”重命名查询的第三个表中的列