Mysql - 使用null简化查询EXIST

时间:2015-10-24 21:48:38

标签: mysql exists

我可以简化这部分查询吗?

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

1 个答案:

答案 0 :(得分:1)

我不确定您为什么首先使用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;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent">

<fragment android:name="com.mamutek.android.protectorx.MainFragment"
          android:id="@+id/headlines_fragment"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="match_parent" />

</LinearLayout>