这个UNION ALL mysql查询有什么问题?

时间:2011-03-27 17:14:53

标签: mysql sql union mysql-error-1064

SELECT 'Q' AS TYPE, 
       q.question AS value, 
       q.date
  FROM questions q
 WHERE q.user_id =39
UNION ALL 
SELECT 'A' AS TYPE, 
       q.question AS value, 
       a.date
  FROM answers a,
       questions q
 WHERE a.question_id = q.id
   AND WHERE a.user_id =39
ORDER BY `date` DESC

数据库设计:

  • 问题{ID,USER_ID,问题,日期}
  • 答案{ID,question_id,USER_ID,答案,日期}

错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'WHERE a'附近使用正确的语法。 user_id = 39 ORDER BY date DESC

4 个答案:

答案 0 :(得分:2)

查询的下半部分有两个WHERE子句。你需要从字面上删除最后一个字WHERE。您只需要错误描述。

答案 1 :(得分:1)

“WHERE”出现两次。其中x = ..... AND ....

答案 2 :(得分:1)

有一个额外的地方a.user_id = 39。您只在子句的开头使用关键字WHERE(a.question_id = q.id AND a.user_id = 39)

SELECT 
'Q' AS TYPE , q.question AS value, q.date
FROM questions q
WHERE q.user_id =39
UNION ALL 
SELECT 'A' AS TYPE , q.question AS value, a.date
FROM answers a,questions q
WHERE a.question_id = q.id
AND
a.user_id =39
ORDER BY `date` DESC

答案 3 :(得分:1)

当错误试图解释时:对于第二个选择,你只需要放一个“WHERE”。

SELECT 'A' AS TYPE , q.question AS value, a.date
FROM answers a,questions q
WHERE a.question_id = q.id
AND
a.user_id =39