[英]SQL match column
Let's assume I have this data.假设我有这些数据。 every person with id, has 2 coupon 1 and 2, which according to way to and back.每个有id的人,有2张优惠券1和2,按照往返的方式。 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 ?是否可以仅提取男性,其中“来自”优惠券 1 列的第 1 行的数据与“至”优惠券 2 列的第 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.因为第 1 行列“来自”优惠券 1 (TSE) 等于第 2 行“到”优惠券 2。
Thank u!感谢你!
With EXISTS
:随着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
.如果从来没有from
等于 to 的情况to
那么您可以删除条件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:你特别提到了优惠券“1”和“2”,所以我会去:
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.请注意,对于列名, to
和from
是非常糟糕的选择,因为它们是SQL 关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.