如果有 2 个同名列,如何 select 左联接中的列? [MySql]

How to select a column in a left join if there is 2 columns with the same name ? [MySql]

我做了一个 LEFT JOIN 来从我的数据库中获取 2 table 的值。
查询是这样的:

SELECT *
FROM thread
  LEFT JOIN comments ON thread.id_thread = comments.id_thread
WHERE id_type = '1'
ORDER BY data DESC, hour DESC

然后我这样输出值:

<?

while($row = mysqli_fetch_array($query))
{
echo '<div class="col-md-1"></div>';
echo '<div class="col-md-11">';
echo  $row['title'] ."<br><br>".$row['content']."<br><br>";
echo  $row['content_com'];
echo '<div class="col-md-2 pull-right">'. "date: ".$row['data']."<br>"."author: ".'<a href ="/user.php?id='.$row['username'].'">'.$row['username'].'</a>'.'</div>' ."<br><br>";
echo '<form role="form" action="commit.php" method="post"><div class="col-md-offset-1 col-md-9"><input class="form-control" type="text" name="comm"><input type="hidden" name="thread_id" value="'.$row['id_thread'].'"></div></form> <br><br><hr><br>';
echo '</div>';
}

mysqli_close($connect);
?>

然后在commit.php(表单动作)中:

<?php
session_start();

  if(isset($_SESSION['id']))
  {
    $servername = "mysql9.000webhost.com";
    $username = "a5461665_admin";
    $password = "xenovia1";
    $dbname = "a5461665_pap";

    $connect  = mysqli_connect($servername, $username, $password, $dbname);

    $id = (isset($_GET['id'])) ? $_GET['id'] : $_SESSION['id'];

    $ctn = $_POST["comm"];

      $com = mysqli_query($connect,"INSERT INTO comments(content_com,id_thread) values ('".$ctn."', '".$_POST['thread_id']."')");

      header("location:javascript://history.go(-1)");


    if (!$connect) {
        die("Connection failed: " . mysqli_connect_error());
    }

}
else
{
  header(" url=index.php");
}


 ?>

我的问题是隐藏的输入框从 table comments 向表单操作传递字段 id_thread 但我希望它传递字段 id_thread 来自 table threads,我该怎么做??

SELECT *, thread.id_thread as mycol
FROM 
thread LEFT JOIN comments 
ON thread.id_thread=comments.id_thread 
WHERE thread.id_type = '1' 
ORDER BY data desc, hour desc

使用 table 指定列名并为其添加别名。 因此,像以前一样对所有列使用 SELECT *,现在采用 thread.id_thread 并将其别名为 mycol。现在将以 mycol 的形式提供,不再有名称冲突。

您可以使用 "alias" 或 table 名称 - 然后指定您要使用的列

SELECT T.*, comments.id_thread AS comment_thread_id
FROM thread T
LEFT JOIN comments 
    ON thread.id_thread=comments.id_thread 
WHERE id_type = '1' ORDER BY  data desc, hour desc

看,T 是 table 名称、线程的 alis,T.* 将 select 来自 thread table 的所有列,comments.id_thread 将仅从 table comments 中获取名为 comment_thread_id

的列 ID

除了使用 aliases/tablename 之外,您还可以使用 USING() 而不是 ON 来连接表。

SELECT T.*, comments.id_thread AS comment_thread_id
FROM thread T
LEFT JOIN comments 
    USING(id_thread) 
WHERE id_type = '1' ORDER BY  data desc, hour desc

这里很好地解释了这两种方法之间的区别: