1

There is a table {id | date}. I want to select all rows where date > date from the given row.

Normally I would do it in two queries:

SELECT `date` FROM `mytable` WHERE `id`={id}; //get {date} from known {id} 

and

SELECT * FROM `mytable` WHERE `date`> {date} //get the desired result 

Is it possible to do it in one SQL query?

Thanks!

1
  • Is it possible to do it in one SQL query? Have you tried it? Commented Oct 30, 2013 at 6:24

2 Answers 2

3
select * from mytable where date > (select date from mytable where id = {id}) 
Sign up to request clarification or add additional context in comments.

Comments

0

This is a good candidate for a self-join.

SELECT o.* FROM mytable t -- For every row from This table, CROSS JOIN mytable o -- and for every row in the Other (see note #2) table WHERE t.id <> o.id -- such that it is a different row AND o.date > t.date -- with a date later AND t.id = {id} -- than a specific row. 

Notes:

  1. Because > is used in the value comparison, the t.id <> o.id clause can be omitted. In any case, the query planner should figure this stuff out just fine.
  2. The CROSS JOIN starts off a Cartesian product but the WHERE filters bring it back down quickly. In particular the t.id = {id} clause (assuming that id has a unique constraint) brings down the multiplicity to at most one output row for each input row in o.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.