我正在尝试通过对匹配最多的人订购记录来改善我的某个网站中的搜索功能。
我有以下mysql表。
SurveyResponses
+--------+-------------+------------------+
| sID | Title | Description |
+--------+-------------+------------------+
| 1 | Set 1 | Some txt here |
| 2 | Set 2 | Other text here |
+--------+-------------+------------------+
数目:
+------+---------+------------+---------+
| aID | Parent | Question | Answer |
+------+---------+------------+---------+
| 1 | 1 | 1 | yes |
| 2 | 1 | 2 | yes |
| 3 | 1 | 3 | yes |
| 4 | 2 | 1 | yes |
| 5 | 2 | 2 | no |
| 6 | 2 | 3 | no |
+------+---------+------------+---------+
我想从SurveyResponses表中获取所有记录,并按照答案表中匹配正确的问题的顺序排序。正确答案如下:
Q1 = yes
Q2 = no
Q3 = no
因此,基于此,查询应返回结果顶部的Set 2,因为答案在该问题的答案表中都是正确的,而q2和q3在集合1中是错误的。
我想我需要某种评分系统,所以我可以做一些像
这样的事情IF q1 = yes THEN score = score + 1
显然我可以在PHP中执行此操作,但不确定在mysql中使用什么方法。
对这个问题的回答将不胜感激,但即使是对最佳方法的暗示或链接也将不胜感激。
答案 0 :(得分:0)
我真的不了解你的设计,或者你正在尝试做什么,而是我会提供一个可能有用也可能没有帮助的替代例子......
CREATE TABLE survey
(question_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,question VARCHAR(100) NOT NULL UNIQUE
,correct_answer VARCHAR(3) NOT NULL
);
INSERT INTO survey VALUES
(1,'Is Rome the capital of Italy?','Yes'),
(2,'Is Paris the capital of England?','No'),
(3,'Is London the capital of Spain?','No');
CREATE TABLE survey_response
(user_id INT NOT NULL
,question_id INT NOT NULL
,response VARCHAR(3) NOT NULL
,PRIMARY KEY(user_id,question_id)
);
INSERT INTO survey_response VALUES
(101,1,'Yes'),
(101,2,'Yes'),
(101,3,'Yes'),
(102,1,'Yes'),
(102,2,'No'),
(102,3,'No');
SELECT * FROM survey;
+-------------+----------------------------------+----------------+
| question_id | question | correct_answer |
+-------------+----------------------------------+----------------+
| 1 | Is Rome the capital of Italy? | Yes |
| 2 | Is Paris the capital of England? | No |
| 3 | Is London the capital of Spain? | No |
+-------------+----------------------------------+----------------+
SELECT * FROM survey_response;
+---------+-------------+----------+
| user_id | question_id | response |
+---------+-------------+----------+
| 101 | 1 | Yes |
| 101 | 2 | Yes |
| 101 | 3 | Yes |
| 102 | 1 | Yes |
| 102 | 2 | No |
| 102 | 3 | No |
+---------+-------------+----------+
因此,假设我想根据谁得到最正确的答案对受访者(user_ids)进行排序。我可以这样做......
SELECT sr.user_id
FROM survey s
JOIN survey_response sr
ON sr.question_id = s.question_id
GROUP
BY user_id
ORDER
BY SUM(sr.response = s.correct_answer) DESC;
+---------+
| user_id |
+---------+
| 102 |
| 101 |
+---------+