Let's assume I have this data. every person with id, has 2 coupon 1 and 2, which according to way to and back. Like this:
ID coupon from to
"1000003328" "1" "TSE" "ALA"
"1000003328" "2" "ALA" "TSE"
"1000009615" "1" "CIT" "ALA"
"1000009615" "2" "ALA" "IST"
"1000014040" "1" "DEL" "ALA"
"1000014040" "2" "ALA" "FRU"
"1000017533" "1" "KBP" "ALA"
"1000017533" "2" "ALA" "PEK"
"1000020561" "1" "ALA" "CIT"
"1000020561" "2" "CIT" "ALA"
"1000026798" "1" "GUW" "SCO"
"1000026798" "2" "SCO" "GUW"
Is it possible to extract only men, where data from row 1 from column "from" coupon 1 match with row2 from column "to" coupon 2 ? This one fits to the abovementioned condititon:
ID coupon from to
"1000003328" "1" "TSE" "ALA"
"1000003328" "2" "ALA" "TSE"
because of row 1 column "from" coupon 1 (TSE) equal to row2 column "to" coupon 2.
Thank u!
With EXISTS
:
select t.* from tablename t
where exists (
select 1 from tablename
where id = t.id and coupon <> t.coupon and "from" = t."to" and "to" = t."from"
)
If there is never a case of from
to be equal to to
then you can remove the condition and coupon <> t.coupon
.
See the demo .
Results:
| id | coupon | from | to |
| ---------- | ------ | ---- | --- |
| 1000003328 | 1 | TSE | ALA |
| 1000003328 | 2 | ALA | TSE |
| 1000020561 | 1 | ALA | CIT |
| 1000020561 | 2 | CIT | ALA |
| 1000026798 | 1 | GUW | SCO |
| 1000026798 | 2 | SCO | GUW |
You specifically reference coupons "1" and "2", so I would go for:
select t.*
from t
where t.coupon in (1, 2) and
exists (select 1
from t t2
where t2.id = t.id and
t2.from = t.to and
t2.to = t.from and
t2.coupon <> t.coupon
);
Note that to
and from
are very poor choices for column names because they are SQL keywords.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.