【问题标题】:SQL query based on ALL or alternative or some other easier way基于 ALL 或替代或其他更简单方式的 SQL 查询
【发布时间】:2018-05-04 22:34:02
【问题描述】:
/* Create a table called NAMES */
CREATE TABLE test(Id integer PRIMARY KEY, group text, content text);

/* Create few records in this table */
INSERT INTO test VALUES(1,'mygroup','foobar');
INSERT INTO test VALUES(2,'myothergroup','foobar');
INSERT INTO test VALUES(3,'myothergroup','foobaz');
INSERT INTO test VALUES(4,'gr1','foobaz');
INSERT INTO test VALUES(5,'gr0','foobaz');
COMMIT;

我有一个类似上面的 SQL 表。

我想找到所有开始我的组中的所有内容。

我的查询如下所示:

SELECT DISTINCT content from test WHERE group like 'my%' and content = 
ALL(SELECT content from test WHERE group like 'my%');

这似乎是无效的,因为它什么都不返回,它应该返回 foobar,因为 foobar 存在于以 my 开头的所有可能的组中。

例如:2

假设我想查找所有以 gr 开头的组中存在的所有内容:

SELECT DISTINCT content from test WHERE group like 'gr%' and content = 
ALL(SELECT content from test WHERE group like 'gr%');

在这里,在这种情况下,它完全可以正常工作并返回 foobaz,因为 foobaz 存在于以 gr 开头的所有可能的组中。

请帮忙。

【问题讨论】:

  • 根本不可能这些是您的数据创建语句。同样适用于您的查询

标签: mysql sql sql-like


【解决方案1】:

你似乎想要:

select content
from test
where group like 'my%'
group by content
having count(distinct group) = (select count(distinct group) from test where group like 'my%');

【讨论】:

    【解决方案2】:

    您只需要一个连接查询

    SELECT DISTINCT t1.content from test t1 join test t2 on t1.Id=t2.Id and t1.group_g like 'my%'
    
    SELECT DISTINCT t1.content from test t1 join test t2 on t1.Id=t2.Id and t1.group_g like 'gr%'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多