我有一张这样的表:
RS Value Measure Feature
1 x1 a 5k
1 x2 b 5k
1 x3 b 10k
1 x4 c 10k
2 y1 a 5k
2 y2 c 5k
2 y3 b 10k
2 y4 d 10k
. . . .
. . . .
. . . .
有差异。 RS的值(如1,2,3,4,......)
现在我想要一个查询(只带两个RS值,这里是1,2),它返回结果如下:
RS Value Measure Feature
1 x1 a 5k
2 y1 a 5k
1 x3 b 10k
2 y3 b 10k
. . . .
. . . .
,即我只想要那些具有共同测量和特征的行。
答案 0 :(得分:1)
为此,您基本上需要在同一查询中两次查看数据并将数据与自身进行比较。有很多方法可以做到这一点,但我能想出的第一个方法就是两次引用该表。
鉴于表格" bar"有了这些数据:
mysql> select * from bar;
+------+-------+---------+---------+
| rs | value | measure | feature |
+------+-------+---------+---------+
| 1 | x1 | a | 5k |
| 1 | x2 | b | 5k |
| 1 | x3 | b | 10k |
| 1 | x4 | c | 10k |
| 2 | y1 | a | 5k |
| 2 | y2 | c | 5k |
| 2 | y3 | b | 10k |
| 2 | y4 | d | 10k |
+------+-------+---------+---------+
8 rows in set (0.00 sec)
根据我对您的要求的解释(这可能是错误的)您想要选择至少有两个条目的所有行,其中度量和特征匹配以及" rs"是两个价值观之一。
我提出的查询如下:
SELECT
bar.rs, bar.value, bar.measure, bar.feature
FROM
bar, bar AS obar
WHERE
( bar.rs == 1 OR bar.rs == 2 )
AND
obar.measure = bar.measure
AND
obar.feature = bar.feature
AND
obar.rs != bar.rs
ORDER BY
measure, rs;
这基本上就是说你想要所有的栏中的所有行,其中obar中有一个匹配的条目(基本上是另一个名称的栏),但rs列的不同之处。
运行查询的结果是:
+------+-------+---------+---------+
| rs | value | measure | feature |
+------+-------+---------+---------+
| 1 | x1 | a | 5k |
| 2 | y1 | a | 5k |
| 1 | x3 | b | 10k |
| 2 | y3 | b | 10k |
+------+-------+---------+---------+
4 rows in set (0.00 sec)
答案 1 :(得分:1)
您可以将此表达为not exists
查询:
select t.*
from table t
where exists (select 1
from table t2
where t2.measure = t.measure and
t2.feature = t.feature and
t2.rs <> t.rs
);