无法弄清楚MySQL语句

时间:2012-07-18 14:39:54

标签: mysql sql mysqli

我的SQL语句看起来像这样

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提前

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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=?