2013-07-24 49 views
-1

我有一個存儲過程像下面的MYSQL:我們如何在MySQL中訂購聯合查詢?

(SELECT 1 AS sort_col, col_a, col_b FROM t1 WHERE col_b LIKE %some% AND col_b LIKE %thing%) 
    UNION 
    (SELECT 2, col_a, col_b FROM t1 WHERE col_b LIKE %some% OR col_b LIKE %thing%) 
ORDER BY sort_col, col_a; 

我想的第一選擇顯示結果在第一,但的一些結果在第二個第一是常見的也是如此,和第二選擇改變了他們的sort_col到2 。(我不能在我的選擇中使用LIMIT) 我能做些什麼來解決它?

回答

2

使用子查詢:

SELECT * FROM 
(
    (SELECT 1 AS sort_col, col1a, col1b FROM t1) 
    UNION 
    (SELECT 2, col2a, col2b FROM t2) 
) tbl 
ORDER BY sort_col, col1a; 

編輯(OP's edit後)

SELECT * FROM 
(
    (SELECT 1 AS sort_col, col_a, col_b 
    FROM t1 
    WHERE col_b LIKE %some% 
     AND col_b LIKE %thing%) 
    UNION 
    (SELECT 2, col_a, col_b 
    FROM t1 
    WHERE col_b LIKE %some% 
     OR col_b LIKE %thing%) 
) tbl 
ORDER BY sort_col, col_a; 
+0

TNX,但它不工作! – Highlan

+0

@Highlan - 這是應該如何工作的。請顯示您的樣本數據和預期結果。 – hims056

+0

請再次看我編輯的問題。 – Highlan