mysql中的sql where子查询

wfveoks0  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(327)

我在mysql中有一个表,

value tag main_tag
1 tag_A ABC
-1 tag_C ABC
-1 tag_A BCD
1 tag_C BCD
-1 tag_A ABC
1 tag_C ABC
-1 tag_A BCD
1 tag_C BCD
-1 tag_C BCD

有三列 value , tag , main_tag . 在每个 main_tag 还有其他几种 tag s。我想得到记录 value 每个的s tag 在每种情况下都等于零 main_tag .
这是我试过的问题,

SELECT * FROM foo WHERE ( WHERE sum(value) = 0 GROUP BY tag) GROUP BY main_tag ;

首先,我试图找到值的和 GROUP BY tag 然后我用 GROUP BY main_tag . 但它不起作用。
输出应为:

value tag main_tag
1 tag_A ABC 
-1 tag_C ABC 
-1 tag_A ABC 
1 tag_C ABC
kxeu7u2r

kxeu7u2r1#

你需要使用 GROUP BY 带的子句 JOIN :

select f.*
from foo f inner join 
           (select distinct tag
            from foo
            group by tag, main_tag
            having sum(value) = 0
          ) f1
          on f1.tag = f.tag;
mdfafbf1

mdfafbf12#

Create table temp select 'value', CONCAT('tag','main_tag') 
as group_tag from your_table;

select group_tag
from temp
group by group_tag
having sum(value) = 0;
iswrvxsc

iswrvxsc3#

这就是你想要的吗?

select main_tag
from foo
group by main_tag
having sum(value) = 0;

相关问题