2014-07-24 230 views
1

如何在一個合併兩個SQL查詢?合併兩個SQL查詢

SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 
SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23 
+1

你想說明你期望的合併結果是什麼嗎? – scragar

回答

2
SELECT * 
FROM TABLE1 
WHERE (CHAPTER = 88 
     AND SENTENCE >= 23) 
     OR (CHAPTER = 89 
      AND SENTENCE >= 1 
      AND SENTENCE <= 23) 
+2

@ gidil:請停止將代碼段編輯爲大寫。它沒有幫助,使得代碼的可讀性往往比更好的更差,並且由OP來格式化代碼,如果它沒有錯誤,那麼請保持原樣。如果一個代碼塊被格式化,OP通常按照他喜歡的方式進行,這很好。 –

5

這是一種方式

SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 
UNION ALL 
SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23 

但你應該進入明確列出列的習慣。列必須對齊,否則將無法工作。

這裏的另一種方式

SELECT * FROM table1 
WHERE (chapter=88 AND sentence>=23) OR (chapter=89 AND sentence>=1 AND sentence<=23) 
5

你可以加入查詢是這樣的:

SELECT * FROM table1 
WHERE 
(chapter = 88 AND sentence >= 23) 
OR 
(chapter = 89 AND sentence >= 1 AND sentence <= 23) 
1

試試這個:

SELECT * FROM table1 
WHERE (chapter=88 and sentence>=23) 
OR (chapter=89 and sentence>=1 and sentence<=23) 

這應該從兩個查詢返回的結果。

2

試試這個:

SELECT * 
FROM TABLE1 
WHERE (CHAPTER = 88 
     AND SENTENCE >= 23) 
     OR (CHAPTER = 89 
      AND SENTENCE BETWEEN 1 AND 23); 
1
SELECT * 
    FROM table1 
WHERE (chapter = 88 AND sentence >= 23) 
    OR (chapter = 89 AND sentence >= 1 AND sentence <= 23) 
2

您已經通過兩種方式處理這樣的表格和

create table table1 (id number, chapter number, sentence number); 

Insert into TABLE1 (ID,CHAPTER,SENTENCE) values (1,65,24); 
Insert into TABLE1 (ID,CHAPTER,SENTENCE) values (2,22,22); 
Insert into TABLE1 (ID,CHAPTER,SENTENCE) values (3,88,25); 
Insert into TABLE1 (ID,CHAPTER,SENTENCE) values (4,89,15); 
Insert into TABLE1 (ID,CHAPTER,SENTENCE) values (4,89,33); 

可以使用工會Munge時間兩部分樣本數據做套在一起

SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 
UNION 
SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23; 

或合併predi凱茨在where子句中實現同樣的事情

SELECT *FROM table1 WHERE (chapter=88 AND sentence>=23) or 
          (chapter=89 AND sentence>=1 AND sentence<=23); 

都將給這個結果

|  ID| CHAPTER| SENTENCE| 
---------------------------------- 
|   3|  88|  25| 
|   4|  89|  15| 
0
Select * 
    From table1 
where ((chapter=88 AND sentence>=23) 
    OR (chapter=89 AND sentence>=1 AND sentence<=23)); 

此外,您還可以使用關鍵字BETWEEN第二子句。

-1
SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 
UNION 
SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23