如何在结果集中避免重复值?

时间:2018-03-12 09:48:53

标签: mysql duplicates database-trigger

CREATE TABLE student (   s_id int(10)NOT NULL AUTO_INCREMENT,   s_roll_no int(30),   s_name varchar(30),   s_gender varchar(4)不为null,   class int(2)not null,   主要关键(s_id) );

CREATE TABLE attendance_date (   date_today varchar(10),   主要关键(date_today) );

CREATE TABLE attendance_today (   s_id int(10),   s_roll_no int(30),   s_name varchar(30),   s_gender varchar(4),   class int(2),   date_today varchar(10),   attendance_status varchar(2)not null默认' P' );

delimiter $$

创建触发器after_insertion_into_attendance_date     在attendance_date上插入后     每行

begin 

insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select * from student cross join attendance_date order by date_today, s_id;

end$$

分隔符;

INSERT INTO student VALUES (1,1,' Mridul Kumar' M',1), (2,2,' Harish Paul' M',1), (3,3,' Imtiaz Hossain' M',1);

INSERT INTO attendance_date VALUES (' 1月1日'), (' 1月2日');

现在, select * from attendance_today; 每次插入后给出重复项,有没有办法避免触发器内部出现重复? 我不是在寻找      从attendance_today中选择distinct *; 触发器激活后。

2 个答案:

答案 0 :(得分:0)

试试这个:

begin 

insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select * from student cross join attendance_date group by s_id order by date_today, s_id;

end$$

答案 1 :(得分:0)

这将防止插入重复的值

insert into attendance_today(s_id, s_roll_no, s_name, s_gender, class, date_today)
select * 
from student cross join attendance_date ad
WHERE NOT EXISTS ( 
    SELECT null FROM attendance_today at
    WHERE ad.s_id = at.s_id and ad.date_today = at.date_today
)
order by date_today, s_id;

```