使用左连接的Mysql查询 - 如果两行相同则使用specialize索引

时间:2017-12-23 19:48:52

标签: php mysql sql-server left-join

我的mysql数据库中有一个名为users的表和另一个名为grouppost的表。两个表都有id行的共同点。所以当我创建一个sql查询时,如果要加入两个表,我怎么能决定我想要哪一行id

实施例

$sql = "SELECT gp.*, u.*
      FROM grouppost
      AS gp LEFT JOIN users AS u ON u.username = gp.author
      WHERE gp.gname = ? AND gp.type = ? ORDER BY gp.pdate DESC $limit";
      $stmt = $conn->prepare($sql);
      $stmt->bind_param("ss",$g,$zero);
      $stmt->execute();
      $result_new = $stmt->get_result();
      if ($result_new->num_rows > 0){
         while ($row = $result_new->fetch_assoc()) {
            $grouppost_id = $row["id"]; // I want to get the id from table grouppost but I get the id from the users table
         }
      }

1 个答案:

答案 0 :(得分:1)

如果要在结果集中单独定位它,可以在select:

中对其进行别名
SELECT gp.*, u.*, gp.id AS grouppost_id 
FROM grouppost AS gp 
LEFT JOIN users AS u ON u.username = gp.author
WHERE gp.gname = ? 
  AND gp.type = ? 
ORDER BY gp.pdate DESC
$limit