使用表连接选择特定数据

时间:2017-02-08 21:02:38

标签: php mysql

我试图通过从问题表中加入来从用户表中输出一些用户用户名,目的是我可以显示哪个用户发布了这个特定问题。

拥有idusername

的用户

discussion_q idquestion_textuser_id

我在这里:

$sql = "SELECT q.id AS questionId, q.question_text AS questionText, q.user_id AS questionUserId, q.published AS questionPub, users.id AS userId 
                    FROM discussion_q 
                    JOIN users
                    ON questionUserId = userId
                    WHERE project_id = '$projectId'
                    ORDER BY published";

我得到0结果当然还给了我。我相信我已经过度设计或错过了一些简单的东西?

这是我的php返回结果:

    $result = $conn->query($sql);
    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo '<div class="twelve columns">
                  <p><a href=".php?project_id=' . $row['id'] .'">' . $row['question_text'] . '</a></p>
                  <p>' . $row['published'] . ' by ' . $row['username'] . '</p>
                  </div>';
        }
    } else {
        echo "0 results";
    }

因此,最终目标是使用发布的用户的用户名输出question_text。

1 个答案:

答案 0 :(得分:0)

$sql = "SELECT q.id AS questionId, q.question_text AS questionText, q.user_id AS questionUserId, q.published AS questionPub, users.id AS userId 
                    FROM discussion AS q 
                    JOIN users
                    ON (q.user_id = users.id)
                    WHERE project_id = '$projectId'
                    ORDER BY published";