输入
+--------+------+------+
| col1 | col2 | col3 |
+--------+------+------+
| apple | d | 10 |
| apple | d | 44 |
| apple | e | 55 |
| orange | d | 99 |
| orange | c | 33 |
| orange | d | 10 |
| banana | e | 55 |
| banana | d | 10 |
+--------+------+------+
Run Code Online (Sandbox Code Playgroud)
要求的输出
+--------+------+------+
| col1 | col2 | col3 |
+--------+------+------+
| apple | d | 10 |
| orange | d | 10 |
| banana | d | 10 |
+--------+------+------+
Run Code Online (Sandbox Code Playgroud)
我们将检查col2和col3的N种不同类型的水果.
我们只想列出那些col2和col3值相同而且所有水果都有行的那些
你可以这样想: -
步骤1
分离出所有不同类型的水果: -
苹果:-
+-------+------+------+
| col1 | col2 | col3 |
+-------+------+------+
| apple | d | 10 |
| apple | d | 44 |
| apple | e | 55 |
+-------+------+------+
Run Code Online (Sandbox Code Playgroud)
橙子:-
+--------+------+------+
| col1 | col2 | col3 |
+--------+------+------+
| orange | d | 99 |
| orange | c | 33 |
| orange | d | 10 |
+--------+------+------+
Run Code Online (Sandbox Code Playgroud)
香蕉:-
+--------+------+------+
| col1 | col2 | col3 |
+--------+------+------+
| banana | e | 55 |
| banana | d | 10 |
+--------+------+------+
Run Code Online (Sandbox Code Playgroud)
第2步:-
现在只选择那些行
和
观察: -
'apple e 55'和'banana e 55'具有相同的col2和col3值,但未选择它,因为'orange e 55'不存在.
如果您使用临时表,请确保它应该是通用的.它应该支持N个水果.
注意: - 这不是学生的作业:D.我用简单的语言解释它,因为它是一个漫长而冗长的查询的一部分,我对如何解决它有零的想法.我一直在使用创建临时表的技术,但我遇到了一些问题.它不是通用的.所以,我相信这个问题可能有更好的解决方案.
基本上,无论name通过此查询,您都可以获得所有水果中的记录,
SELECT col2, col3
FROM tableName
GROUP BY col2, col3
HAVING COUNT(*) = (SELECT COUNT(DISTINCT col1) FROM tableName)
Run Code Online (Sandbox Code Playgroud)
一组两列中的记录总数:col2并且col3必须等于结果总数.SELECT COUNT(DISTINCT col1) FROM tableName.
因此,要获得所有水果中存在组合的所有记录,我们需要JOIN使用表格本身.
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT col2, col3
FROM tableName
GROUP BY col2, col3
HAVING COUNT(*) = (SELECT COUNT(DISTINCT col1) FROM tableName)
) b ON a.col2 = b.col2 AND
a.col3 = b.col3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |