PHP帮助Inner Join问题mysqli

时间:2015-07-27 08:36:47

标签: php mysql

我需要针对来自users表的user_id显示来自表票证的支持票证。我正在使用MySQLI。这是我写的查询,但对我来说不起作用:

SELECT user_id, subject, message FROM tickets 
INNER JOIN users.user_id WHERE user_id='".$user_id."'"

任何人都可以更正此查询吗?

这里的完整代码

<?php
$servername = "localhost";
$username = "d";
$password = "ddds";
$dbname = "sddd";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT user_id, subject, message FROM tickets INNER JOIN users.user_id USING (user_id) WHERE user_id='".$user_id."'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table class='table table-bordered'>
         <thead>
            <tr>                                                
              <th>Subject</th>
              <th>Date</th>
              <th>Status</th>
              <th>View</th>
            </tr>
           </thead>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["subject"]."</td><td>".$row["date"]." ".$row["status"]."</td><td>".$row["view"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?> 

3 个答案:

答案 0 :(得分:1)

更正语法:

SELECT T.user_id, T.subject, message FROM tickets T 
INNER JOIN users U ON U.user_id = T.user_id WHERE `T.user_id='".$user_id."'"`

您已忘记ON

答案 1 :(得分:0)

如果您想使用INNER JOIN,则必须指定您正在进行加入的位置(使用onusing),例如以下查询:

SELECT user_id, subject, message 
FROM tickets 
INNER JOIN users.user_id ON tickets.user_id = users.user_id 
WHERE user_id = '".$user_id."'"

OR

SELECT user_id, subject, message 
FROM tickets 
INNER JOIN users.user_id USING (user_id) 
WHERE user_id = '".$user_id."'" 

答案 2 :(得分:0)

你应该只加入表而不是字段!

SELECT user_id, subject, message FROM tickets 
INNER JOIN users.user_id WHERE user_id='".$user_id."'"

tickets表加入users.user_id表,该表是users表的字段。应该是:

SELECT user_id, subject, message FROM tickets 
INNER JOIN users USING (user_id) WHERE user_id='".$user_id."'"

您也可以使用ON进行连接(当列名称匹配时使用是一个快捷方式):

SELECT user_id, subject, message FROM tickets 
INNER JOIN users ON tickets.user_id=users.user_id WHERE user_id='".$user_id."'"