回答編集履歴

1 chousei

yambejp

yambejp score 86609

2019/02/12 12:50  投稿

問題id、ユーザーid、correct、answer_at
を保持するテーブルがあればよいのでは?
answer_atは未回答のときにはnullもしくは果てしない未来日として
回答した時点で日時を入れれば、answer_atが過去日で
correctが0のモノが間違えた質問になります
correctが0のモノが間違えた質問になります
# 訂正
なんか効率悪そうなので考え方を換えます
```SQL
create table question(qid int primary key,qtext varchar(100)
,a1 varchar(100)
,a2 varchar(100)
,a3 varchar(100)
,a4 varchar(100)
,correct_a int);
insert into question values
( 1,"q01_text","q01_a1","q01_a2","q01_a3","q01_a4",1),
( 2,"q02_text","q0_a1","q02_a2","q02_a3","q02_a4",2),
( 3,"q03_text","q03_a1","q03_a2","q03_a3","q03_a4",3),
( 4,"q04_text","q04_a1","q04_a2","q4_a3","q4_a4",3),
( 5,"q05_text","q05_a1","q05_a2","q5_a3","q5_a4",4),
( 6,"q06_text","q06_a1","q06_a2","q6_a3","q6_a4",2),
( 7,"q07_text","q07_a1","q07_a2","q7_a3","q7_a4",1),
( 8,"q08_text","q08_a1","q08_a2","q8_a3","q8_a4",3),
( 9,"q09_text","q09_a1","q09_a2","q9_a3","q9_a4",4),
(10,"q10_text","q10_a1","q10_a2","q0_a3","q0_a4",4),
(11,"q11_text","q11_a1","q11_a2","q1_a3","q1_a4",1);
create table user(uid int primary key,uname varchar(20));
insert into user values(1,'u1'),(2,'u2'),(3,'u3');
create table user_question(uqid int primary key auto_increment,uid int not null,qid int not null,correct tinyint default 0,unique(uid,qid));
insert into user_question(uid,qid,correct) values
(1,1,1),
(1,2,1),
(1,3,1),
(1,4,0),
(1,5,0),
(1,6,0),
(2,1,1),
(2,2,0),
(2,3,1),
(2,4,0),
(2,5,1),
(2,6,0);
```
だとします。
上記条件からuid=1の場合qid=1,2,3を除くもの、uid=2の場合qid=1,3,5を除くもの
uid=3の場合すべてが対象になります。
# 抽出
```SQL
select * from question as t1
where not exists(select 1 from user_question where qid=t1.qid and uid=1 and correct=1)
```
uid=xxのxxを指定すれば間違っていたものおよび未回答の物が表示されます。
1問だけ表示したいならorder by とlimitを併用します
```SQL
select * from question as t1
where not exists(select 1 from user_question where qid=t1.qid and uid=1 and correct=1)
order by rand()
limit 1
```

思考するエンジニアのためのQ&Aサイト「teratail」について詳しく知る