2013-11-15 70 views
0

我正在嘗試通過訂購最匹配的記錄來改進我的搜索功能。給予mysql權重搜索結果

我有以下的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 

所以在此基礎上,查詢應該在結果頂部返回集2,因爲答案是在答案表這個問題正確的,而Q2和Q3分別爲錯在組1

我想我需要某種形式的評分系統,這樣我就可以這樣做

IF q1 = yes THEN score = score + 1 

很顯然,我可以做到這一點在PHP中,但不知道在MySQL使用什麼方法。

對這個問題的答案將不勝感激,但即使是最好的方法提示或鏈接將不勝感激。

+0

「正確的答案如下:」這不是你想要存儲在數據庫中的東西! – Strawberry

+0

我不關注。數據存儲在數據庫中 - 我只想知道如何訂購它!你是否建議增加一列來簡單地保留'分數'? –

+0

「我不遵循。」你和我都:-) – Strawberry

回答

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 | 
+---------+ 
+0

非常有幫助 - 把我放在正確的道路上。謝謝。 –