简体   繁体   English

从两行中删除一行,将相同的值交替显示在两列中

[英]Delete one row out of two with same values alternating in two different columns

The query goes like this: 查询如下:

select g1.gen_id as 'gen_1', g2.gen_id as 'gen_2', count(*) as 'count'
from gen g1, gen g2, dir d
where g1.gen_id <> g2.gen_id
[other irrelevant where conditions here]
order by g1.gen_id, g2.gen_id;

The output becomes: 输出变为:

# gen_1, gen_2, count
'32', '34', '5'
'34', '32', '5'
'32', '39', '2'
'32', '40', '2'
'32', '42', '1'
'32', '43', '3'
'39', '32', '2'
'43', '32', '3'
'32', '45', '4'
'32', '48', '1'
'40', '32', '2'

As you can see, this occurs because I'm getting the cartesian product of the same table (I have it in the from clause twice). 如您所见,发生这种情况是因为我得到了同一张表的笛卡尔积(我在from子句中有两次)。 If you'll notice in the output, I have values alternating in two of the columns (the first 2 columns - the third column is irrelevant here). 如果您在输出中注意到,则在两列中交替显示值(前两列-此处与第三列无关)。 What I want is to remove one row of each one of those duplicates. 我要删除的是每一个重复项的一行。 I didn't paste the entire output, but rest assured this is what happens. 我没有粘贴整个输出,但是请放心,这就是发生的情况。 I have 442 lines output when they should be 221. I want to remove the "duplicate" lines. 当有221行时,我有442行输出。我想删除“重复”行。 Is there a way to do this, because I can't find a way around currently. 有没有办法做到这一点,因为我目前找不到解决方法。

The solution is to use < . 解决方案是使用< However, I would make a few other changes to the query: 但是,我将对查询进行其他一些更改:

select g1.gen_id as gen_1, g2.gen_id as gen_2, count(*) as cnt
from gen g1 join
     gen g2, dir d
     on g1.gen_id < g2.gen_id
where [other irrelevant where conditions here]
order by g1.gen_id, g2.gen_id;

First, this uses explicit join syntax. 首先,这使用显式join语法。 Although not strictly necessary, JOIN does a better job than , of expressing what you want to accomplish. 虽然不是绝对必要, JOIN确实比一个更好的工作,表达你想要完成的任务的。

Second, it removes the single quotes around the column names. 其次,它删除列名周围的单引号。 Only use single quotes for string and date constants. 仅对字符串和日期常量使用单引号。 Otherwise, you're code might break, when a column alias is interpreted as a string. 否则,当列别名被解释为字符串时,您的代码可能会中断。

Use 采用

where g1.gen_id > g2.gen_id

or 要么

where g1.gen_id < g2.gen_id

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM