Home > Software design >  How can I select rows with an extra column joined from the same table
How can I select rows with an extra column joined from the same table

Time:03-02

I have a table like this:

id | path      | name | date       | data
--- ----------- ------ ------------ -----
1  | Docs      | 1000 | 2022-01-01 | aaa0
2  | Docs/1000 | Text | 2022-01-11 | AAA0
3  | Docs      | 1001 | 2022-02-02 | aaa1
4  | Docs/1001 | Text | 2022-02-12 | AAA1

How can I select all rows with path 'Docs' and add the date of the corresponding 'Text', i.e:

id | path | name | date       | date_of_text | data
--- ------ ------ ------------ -------------- -----
1  | Docs | 1000 | 2022-01-01 | 2022-01-11   | AAA0
3  | Docs | 1001 | 2022-02-02 | 2022-02-12   | AAA1

CodePudding user response:

You can achieve the desired result with self join -

SELECT T1.id, T1.path, T1.name, T1.date, T2.date date_of_text, T2.data
  FROM table_name T1
  LEFT JOIN table_name T2 ON T1.name = SUBSTRING(path, POSITION("/" IN path)   1, LENGTH(path))
 WHERE T1.path = 'Docs'

CodePudding user response:

Lots of ways to do this including

correlated sub query

select t.*,id % 2 ,(select date from t t1 where t1.ID = t.id   1) datetext
from t
where id % 2 > 0;

self join

select t.*,t.id % 2 , t1.date
from t
join t t1 on t1.ID = t.id   1
where t.id % 2 > 0;

Aggregation

select min(id) id,min(path) path,min(date) date,upper(data) data ,max(date) datetext
from t
group by t.data;
  • Related