如何在 mysql 查询中筛选确定数量的行?
How to filter a determined quantity of rows in a mysql query?
我试图在 MySQL 查询中使用 HAVING
语句获取特定结果。让我更好地解释一下:
我有以下 table 结构 +data:
| ID | COLUMN1| COLUMN2|
|----|--------|--------|
|1 | 52 | APPLE |
|2 | 52 | APPLE |
|3 | 58 | ORANGE |
|4 | 58 | ORANGE |
|5 | 61 | ORANGE |
|6 | 50 | ORANGE |
|7 | 50 | ORANGE |
|8 | 58 | LEMON |
|9 | 58 | LEMON |
|10 | 53 | LEMON |
|11 | 53 | LEMON |
当我提交此查询时:
select column1, column2, count(column2)
from new_table
group by column1, column2
having count(column2) > 1
order by column2;
结果如下:
'52', 'APPLE', '2'
'53', 'LEMON', '2'
'58', 'LEMON', '2'
'50', 'ORANGE', '2'
'58', 'ORANGE', '2'
但是,实际上,我想隐藏只出现在一个 colum1 中的所有结果,因此,我想隐藏 'APPLE' 行,因为这两个事件来自同一个 Column1 (52) .我想要以下结果:
'53', 'LEMON', '2'
'58', 'LEMON', '2'
'50', 'ORANGE', '2'
'61', 'ORANGE', '1'
'58', 'ORANGE', '2'
您可以使用此查询:
SELECT column2
FROM new_table
GROUP BY column2
HAVING COUNT(DISTINCT column1) > 1
获得 column2
个与 多个 column1
个值相关的值。
如果您在查询中包含以上内容,您将获得:
SELECT column1, column2, count(column2) AS cnt
FROM new_table
WHERE column2 IN (SELECT column2
FROM new_table
GROUP BY column2
HAVING COUNT(DISTINCT column1) > 1)
GROUP BY column1, column2
ORDER BY column2;
您只想 select 存在具有另一个值的记录的水果,因此使用 WHERE EXISTS
。然后聚合每个水果得到一个结果行和记录数。
select column1, column2, count(*)
from new_table
where exists
(
select *
from new_table other
where other.column2 = new_table.column2
and other.column1 <> new_table.column1
)
group by column1, column2;
我试图在 MySQL 查询中使用 HAVING
语句获取特定结果。让我更好地解释一下:
我有以下 table 结构 +data:
| ID | COLUMN1| COLUMN2|
|----|--------|--------|
|1 | 52 | APPLE |
|2 | 52 | APPLE |
|3 | 58 | ORANGE |
|4 | 58 | ORANGE |
|5 | 61 | ORANGE |
|6 | 50 | ORANGE |
|7 | 50 | ORANGE |
|8 | 58 | LEMON |
|9 | 58 | LEMON |
|10 | 53 | LEMON |
|11 | 53 | LEMON |
当我提交此查询时:
select column1, column2, count(column2)
from new_table
group by column1, column2
having count(column2) > 1
order by column2;
结果如下:
'52', 'APPLE', '2'
'53', 'LEMON', '2'
'58', 'LEMON', '2'
'50', 'ORANGE', '2'
'58', 'ORANGE', '2'
但是,实际上,我想隐藏只出现在一个 colum1 中的所有结果,因此,我想隐藏 'APPLE' 行,因为这两个事件来自同一个 Column1 (52) .我想要以下结果:
'53', 'LEMON', '2'
'58', 'LEMON', '2'
'50', 'ORANGE', '2'
'61', 'ORANGE', '1'
'58', 'ORANGE', '2'
您可以使用此查询:
SELECT column2
FROM new_table
GROUP BY column2
HAVING COUNT(DISTINCT column1) > 1
获得 column2
个与 多个 column1
个值相关的值。
如果您在查询中包含以上内容,您将获得:
SELECT column1, column2, count(column2) AS cnt
FROM new_table
WHERE column2 IN (SELECT column2
FROM new_table
GROUP BY column2
HAVING COUNT(DISTINCT column1) > 1)
GROUP BY column1, column2
ORDER BY column2;
您只想 select 存在具有另一个值的记录的水果,因此使用 WHERE EXISTS
。然后聚合每个水果得到一个结果行和记录数。
select column1, column2, count(*)
from new_table
where exists
(
select *
from new_table other
where other.column2 = new_table.column2
and other.column1 <> new_table.column1
)
group by column1, column2;