2011-05-25 29 views
1

的一部分,我有一個聯合查詢,如下所示: MySQL查詢:使用UNION和獲得的行號SELECT

 
(SELECT t.id, t.name, c.company AS owner, t.creation_date AS date, t.notes 
FROM tool t, client c 
WHERE t.id_customer = '15' AND t.trash_flag = '1') 
    UNION 
(SELECT f.id, f.name, CONCAT(m.first_name, ' ', m.last_name) AS owner, f.date, f.notes 
FROM file f, meta m 
WHERE ((f.acl = 0) OR (f.acl = 1 AND '1' = TRUE) OR (f.acl = 2 AND f.id = '7')) AND f.id = '15' AND f.trash_flag = '1' AND m.user_id = f.id_user) 
ORDER BY 'name' 'ASC' LIMIT 0,20 
一切工作正常,但我有兩個問題:

  1. 如何添加一列到整個結果集,給出行號
  2. 我可以做到這一點,而不使用UNION例如高級加入?

感謝您的時間MySQL專家!

回答

2

我不能測試它現在右擊但我發現,以下可能的工作:

參考:Row Number Variable

SQL語句

SELECT @rownum := @rownum + 1 rownum 
     , t.* 
FROM (
      (SELECT t.id 
        , t.name 
        , c.company AS owner 
        , t.creation_date AS date 
        , t.notes 
      FROM tool t 
        , client c 
      WHERE t.id_customer = '15' 
        AND t.trash_flag = '1' 
      ) UNION (
      SELECT f.id 
        , f.name 
        , CONCAT(m.first_name, ' ', m.last_name) AS owner 
        , f.date 
        , f.notes 
      FROM file f 
        , meta m 
      WHERE ((f.acl = 0) OR (f.acl = 1 AND '1' = TRUE) OR (f.acl = 2 AND f.id = '7')) AND f.id = '15' AND f.trash_flag = '1' AND m.user_id = f.id_user) 
      ) 
     ) t 
     , (SELECT @rownum := 0) r 
ORDER BY 
     'name' ASC 
LIMIT 0, 20 
+0

+1'ORDER按名稱ASC LIMIT 0,20'可能意味着在外部選擇,但這是正確的。 – 2011-05-25 11:05:20

+1

除了'UNION ALL'外,還有一件事情可以加快查詢的速度:您可以在子查詢和外部查詢中添加一個「LIMIT 0,20」。 – 2011-05-25 11:05:44

+0

@ypercube,謝謝。我已經實施了您的更正和建議。 – 2011-05-25 11:11:18