Doro
Doro

Reputation: 671

SQLite: Joining two select statements

I have two select statements and I am looking for a way to join them into one. Thank you for any help and advice.

Original:
1
2
3
4
5
6

Sql:
Select * From (Select * From tbl1 Where Id < 4 Order By Id Desc Limit 1) Order By Id;
Select * From tbl1 Where Id >= 4 Order By Id;

Result:
3
4
5
6

Upvotes: 1

Views: 8309

Answers (2)

What's the point in using this:

Select * From (Select * From tbl1 Where Id < 4 Order By Id Desc Limit 1) Order By Id;

Isn't this enough?:

Select * From tbl1 Where Id < 4 Order By Id Desc Limit 1

Anyways, you can use SQL UNION for this.

(SELECT * FROM tbl1 WHERE Id < 4 ORDER BY Id DESC LIMIT 1)
UNION
(SELECT * FROM tbl1 WHERE Id >= 4 ORDER BY Id ASC)
ORDER BY Id

Your first query can be considered as an entire table. Likewise, your 2nd query can be considered as another table.

Then, using the SQL operator UNION, you can get a combined resultset, joining those two 'tables'.

For more details, please go through the following link: http://www.w3schools.com/sql/sql_union.asp

Upvotes: 3

Andr&#233; Stannek
Andr&#233; Stannek

Reputation: 7863

Looks like you could use a UNION SELECT.

Select * From (Select * From tbl1 Where Id < 4 Order By Id Desc Limit 1)
UNION Select * From tbl1 Where Id >= 4
Order By Id;

Works only if the result of the two statements has the same column count and types.

Upvotes: 3

Related Questions