0

我的 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_id0,则

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_id0 那么

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

3 回答 3

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=?
于 2012-07-18T14:51:03.147 回答
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 中可以做到的

于 2012-07-18T14:49:12.797 回答
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
于 2012-07-18T14:49:51.820 回答