使用sql按族返回行

btxsgosb  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(296)

这是我在stackoverflow的第一个问题,所以请对我好一点:)
我有一个具有列族的表,当我进行查询(使用where语句)时,我希望将结果显示为具有相同族的一组行
例如,表为shop:

+----+--------+-------+
| id | family | money |
+----+--------+-------+
|  1 |      1 |   100 |
|  2 |      1 |    70 |
|  3 |      2 |    10 |
|  4 |      2 |    20 |
|  5 |      3 |    50 |
+----+--------+-------+

所以在执行这样的查询时:

SELECT * FROM shop where money=100 --(adding to the query of course what's needed)

它将选择以下两个:

+-----+----------+---------+
| id  |  family  |  money  |
+-----+----------+---------+
| 1   |       1  |    100  |
| 2   |       1  |     70  |
+-----+----------+---------+
wbgh16ku

wbgh16ku1#

你可以用 in 或者 exists :

SELECT s.*
FROM shop 
WHERE s.family IN (SELECT s2.family FROM shop s2 WHERE s2.money = 100);
kkih6yb8

kkih6yb82#

可以将相关子查询与 Exists() :

SELECT
  t1.*
FROM shop t1
WHERE EXISTS (SELECT 1 FROM shop t2
              WHERE t2.family = t1.family AND 
                    t2.money = 100)

相关问题