Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a single SQL correlated sub-query to get two columns

My problem is represented by the following query:

SELECT 
  b.row_id, b.x, b.y, b.something,
  (SELECT a.x FROM my_table a WHERE a.row_id = (b.row_id - 1), a.something != 42 ) AS source_x,
  (SELECT a.y FROM my_table a WHERE a.row_id = (b.row_id - 1), a.something != 42 ) AS source_y
FROM 
  my_table b

I'm using the same subquery statement twice, for getting both source_x and source_y. That's why I'm wondering if it's possible to do it using one subquery only?

Because once I run this query on my real data (millions of rows) it seems to never finish and take hours, if not days (my connection hang up before the end).

I am using PostgreSQL 8.4

like image 796
Julie F-C Avatar asked Nov 06 '11 19:11

Julie F-C


People also ask

Can a sub query return multiple columns?

SQL: Multiple Column Subqueries You can write subqueries that return multiple columns.

How do I subquery with multiple columns?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.


1 Answers

I think you can use this approach:

SELECT b.row_id
     , b.x
     , b.y
     , b.something
     , a.x
     , a.y
  FROM my_table b
  left join my_table a on a.row_id = (b.row_id - 1)
                      and a.something != 42
like image 102
DavidEG Avatar answered Oct 04 '22 11:10

DavidEG