在MySQL中,如何从一行查询两列?
在MySQL表中,每次信用卡余额从一张卡转移到另一张卡时,cardToCard都有一行在MySQL中,如何从一行查询两列?,mysql,sql,join,union,Mysql,Sql,Join,Union,在MySQL表中,每次信用卡余额从一张卡转移到另一张卡时,cardToCard都有一行 create table cardToCard ( id int, dt date, card_from int, card_to int, amount decimal(6,2), primary key (id) ); insert into cardToCard values (1, '2014-01-01', 100, 101, 200.00); insert into c
create table cardToCard (
id int,
dt date,
card_from int,
card_to int,
amount decimal(6,2),
primary key (id)
);
insert into cardToCard values (1, '2014-01-01', 100, 101, 200.00);
insert into cardToCard values (2, '2014-01-01', 101, 102, 200.00);
insert into cardToCard values (3, '2014-01-01', 102, 103, 200.00);
insert into cardToCard values (4, '2014-01-01', 103, 104, 200.00);
insert into cardToCard values (5, '2014-01-01', 104, 100, 200.00);
insert into cardToCard values (6, '2014-01-01', 99, 104, 200.00);
查询哪张卡已使用3次或以上
select card, count(*) 'count'
from
(
select card_from 'card', dt
from cardtocard
union all
select card_to 'card', dt
from cardtocard
) d
group by card
having count >= 3
结果是正确的。问题是,将此作为自联接编写会更有效吗
编写此查询最有效的方法可能是从卡片列表开始,然后执行以下操作:
select c.card,
((select count(*) from cardTocard ctc where ctc.card_from = c.card) +
(select count(*) from cardTocard ctc where ctc.card_to = c.card)
) as cnt
from cards c
having cnt >= 3;
然后,您需要两个索引:cardTocard(card\u-from)
和cardTocard(card\u-to)
这应该使用聚合的索引,这通常比文件排序快
编辑:
使用您正在使用的结构,可以更快地在子查询和外部查询中进行聚合:
select card, sum(cnt) as cnt
from ((select card_from as car, count(*) as cnt
from cardtocard
group by card_from
) union all
(select card_to as card, count(*) as cnt
from cardtocard
group by card_to
)
) d
group by card
having count >= 3;
这可以更快,因为子查询的数据量小于将它们合并在一起的数据量。Picard:“你确定吗,数据先生?”;-)@安托尼拉特利奇。不,我不确定。和大多数性能推测一样,它应该在特定的系统上进行验证。问题是c.card不存在,不确定如何修复它。