如何管理mysql中的联系

时间:2015-06-03 17:14:29

标签: mysql stored-procedures

我有这张桌子

CREATE TABLE `autores` (
`id_autor` int(11) NOT NULL DEFAULT '0',
`login` varchar(60) NOT NULL DEFAULT '',
`password` varchar(64) NOT NULL DEFAULT '',
`correo` varchar(100) NOT NULL DEFAULT '',
`url` varchar(100) NOT NULL DEFAULT '');

CREATE TABLE `noticias` (
`id` int(11) NOT NULL DEFAULT '0',
`autor_id` char(15) NOT NULL DEFAULT '0',
`fecha_pub` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`contenido` longtext NOT NULL,
`titulo` text NOT NULL,
UNIQUE KEY `in1` (`id`),
FULLTEXT KEY `full` (`titulo`,`contenido`)
) ENGINE=MyISAM AUTO_INCREMENT=3844 DEFAULT CHARSET=latin1;

现在我已经创建了一个程序,可以计算出作者中谁拥有最多"文章"公布

create procedure masnoticiasmes(in mes int)
begin
declare empate int default 0;
declare nombreautor VARCHAR(30);
declare cantidad, autor, autormax int;
declare maximo, fin  int default 0;
declare nombreautor2,nombreempate char(30);
declare empatado char(30);
declare micursor cursor for select count(id), autor_id  from noticias where month(fecha_pub)=mes group by autor_id;
declare continue handler for not found set fin=1;
open micursor;
repeat
fetch micursor into cantidad, autor;
if fin=0 then
if cantidad>maximo  then 
set maximo=cantidad;
set autormax=autor;
set empate=0;      
end if;
if cantidad=maximo and autormax != autor then

set empatado=autor;
set empate=empate+1;
end if;
end if;
until fin end repeat;
select login from autores join noticias on  noticias.autor_id=autores.id_autor where cantidad IN (maximo) into nombreempate;
close micursor;

select login from autores join noticias on noticias.autor_id=autores.id_autor where autores.id_autor=empatado into nombreempate;

select concat ( "El que mas ha publicado es el: ", nombreautor2," con ", maximo, " noticias ", " empatados ", empate,nombreempate) as "resultado";
end//

现在我的问题是,当发生平局时,我不得不说

发表最多的作者是X(由于光标的工作方式,即使有一个平局,它也会获得第一个发布最多的作者)然后它说有X个关系 并且有一个平局的作者是X,问题是出版物最多的作者是一个变量,当两者之间存在关系时它工作正常,只需从表中选择作者姓名,其中id是作者身份。 但如果有超过2个作者,我将不得不将名称存储在一个变量中,每个作者的1个变量只是不可行的,你会怎么做?

0 个答案:

没有答案