Mysql - 使用 null 简化查询 EXIST
Mysql - simplify query EXIST with null
我可以简化这部分查询吗?
CASE WHEN EXISTS(SELECT a_response from answer where a_userID = ? AND a_questionID = q_id)
THEN (SELECT a_response from answer where a_userID = ? AND a_questionID = q_id) ELSE null END
或完成查询:
SELECT q_id, q_question, q_userID, q_targetID, concat(u_firstname, ' ',u_lastname),
CASE WHEN EXISTS(SELECT a_response from answer where a_userID = ? AND a_questionID = q_id)
THEN (SELECT a_response from answer where a_userID = ? AND a_questionID = q_id) ELSE null END,
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id AND a_response = 1)
FROM question INNER JOIN user ON q_userID = u_id
where q_targetID = ?
ORDER BY q_created DESC LIMIT ?, 10
我不确定您一开始为什么要使用 exists
。子查询将正常工作。如果没有行,标量子查询 returns NULL
:
SELECT q_id, q_question, q_userID, q_targetID,
concat(u_firstname, ' ', u_lastname),
(SELECT a_response FROM answer WHERE a_userID = ? AND a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id AND a_response = 1)
FROM question INNER JOIN
user
ON q_userID = u_id
WHERE q_targetID = ?
ORDER BY q_created DESC
LIMIT ?, 10;
我可以简化这部分查询吗?
CASE WHEN EXISTS(SELECT a_response from answer where a_userID = ? AND a_questionID = q_id)
THEN (SELECT a_response from answer where a_userID = ? AND a_questionID = q_id) ELSE null END
或完成查询:
SELECT q_id, q_question, q_userID, q_targetID, concat(u_firstname, ' ',u_lastname),
CASE WHEN EXISTS(SELECT a_response from answer where a_userID = ? AND a_questionID = q_id)
THEN (SELECT a_response from answer where a_userID = ? AND a_questionID = q_id) ELSE null END,
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id AND a_response = 1)
FROM question INNER JOIN user ON q_userID = u_id
where q_targetID = ?
ORDER BY q_created DESC LIMIT ?, 10
我不确定您一开始为什么要使用 exists
。子查询将正常工作。如果没有行,标量子查询 returns NULL
:
SELECT q_id, q_question, q_userID, q_targetID,
concat(u_firstname, ' ', u_lastname),
(SELECT a_response FROM answer WHERE a_userID = ? AND a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id),
(SELECT count(a_id) FROM answer WHERE a_questionID = q_id AND a_response = 1)
FROM question INNER JOIN
user
ON q_userID = u_id
WHERE q_targetID = ?
ORDER BY q_created DESC
LIMIT ?, 10;