2012-07-18 67 views
0

我的SQL語句看起來像這樣想不通的MySQL聲明

SELECT q.content 
FROM questions AS q, user_question_assoc AS uqa 
WHERE uqa.user_id=? AND (q.course_id = uqa.course_id 
OR q.lesson_id=uqa.lesson_id 
OR q.question_id=uqa.question_id) 

聲明的最後一部分是不是因爲我需要

WHERE uqa.user_id=? AND (q.course_id = uqa.course_id 
    OR q.lesson_id=uqa.lesson_id 
    OR q.question_id=uqa.question_id) 

其實我想弄清楚1,僅在MySQL聲明從以下(我試過在人類的語言來解釋))

如果uqa.question_id不爲0(或NULL)則

WHERE uqa.user_id=? AND (q.course_id = uqa.course_id 
     AND q.lesson_id=uqa.lesson_id 
     AND q.question_id=uqa.question_id) 

如果uqa.lesson_id不爲0(或NULL),但uqa.question_id是0,那麼

WHERE uqa.user_id=? AND (q.course_id = uqa.course_id 
     AND q.lesson_id=uqa.lesson_id) 

如果uqa.course_id不爲0(或NULL),但uqa.question_iduqa.lesson_id是0,那麼

WHERE uqa.user_id=? AND q.course_id = uqa.course_id 

有什麼建議? THX提前

回答

1

我認爲你可以使用情況下,如:

WHERE (CASE WHEN xx is not null then xid when yyx is null the yid end) = (CASE WHEN ww is null then someother id else id end) 

我不知道MySQL的語法,但是這是它如何能在Oracle或MS SQL進行

1

一些如果您使用OR子句,則數據庫(如MySQL)不會使用索引。使用UNION而是可以與大表性能要好得多:

SELECT 
    1 AS id, 
    q.content 
FROM 
    questions AS q 
INNER JOIN 
    user_question_assoc AS uqa ON 
     q.course_id = uqa.course_id AND 
     q.lesson_id = uqa.lesson_id AND 
     q.question_id = uqa.question_id 
WHERE 
    uqa.user_id  = ? AND 
    uqa.question_id <> 0 
UNION 
SELECT 
    2 AS id, 
    q.content 
FROM 
    questions AS q 
INNER JOIN 
    user_question_assoc AS uqa ON 
     q.course_id = uqa.course_id AND 
     q.lesson_id = uqa.lesson_id 
WHERE 
    uqa.user_id  = ? AND 
    uqa.question_id = 0 
UNION 
SELECT 
    3 AS id, 
    q.content 
FROM 
    questions AS q 
INNER JOIN 
    user_question_assoc AS uqa ON 
     q.course_id = uqa.course_id 
WHERE 
    uqa.user_id  = ? AND 
    uqa.question_id = 0 AND 
    uqa.lession_id = 0 
1

首先,你應該這樣做使用適當的聯接語法:

SELECT q.content 
FROM questions q join 
    user_question_assoc uqa 
    on (q.course_id = uqa.course_id OR 
     q.lesson_id=uqa.lesson_id OR 
     q.question_id=uqa.question_id) 
WHERE uqa.user_id=? 

現在試試這個:

SELECT q.content 
FROM questions q join 
    user_question_assoc uqa 
    on q.course_id = uqa.course_id AND 
     (q.lesson_id=uqa.lesson_id OR coalesce(uqa.lesson_id, 0) = 0) AND 
     (q.question_id=uqa.question_id or coalesce(uqa.question_id, 0) = 0) 
WHERE uqa.user_id=?