dongzhuji1042 2017-02-08 21:02
浏览 59
已采纳

使用表连接选择特定数据

I am attempting to output some a user username from the user table by joining it from a questions table, the intention being I can show which user posted this specific question.

users with id, username

discussion_q id, question_text, user_id

Here is where I am at:

$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";

I am getting 0 results returned back to me of course. I am sure I have over engineered this or missed something simple?

Here is my php to return the results:

    $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";
    }

So the end goal is to output the question_text with the username of the user who posted.

  • 写回答

1条回答 默认 最新

  • dongzhuzhou4504 2017-02-08 21:05
    关注
    $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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面