php - 带左连接的 Mysql 查询 - 如果两行相同则专用索引

标签 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
         }
      }

最佳答案

如果您想在结果集中单独定位它,您可以在选择中为其指定别名:

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

关于php - 带左连接的 Mysql 查询 - 如果两行相同则专用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47955497/

相关文章:

mysql - 如何根据MySQL中其他列的值创建新列

python - 将数据写入 SQL Server

php - mysql 将关联提取到列中

php - 如果时间戳范围在时间戳范围内

php - 日期和时间错误 12-31-1969, 7 :00 PM

mysql密码弄乱了我的转储

asp.net - ASP.NET网站管理工具:无法连接到SQL Server数据库

sql-server - ADO.NET 与 SSMS 中的 SQL Server 性能对比

php - 在 Apigility 中使用 "DB Connect"生成新服务时出错

php - 将文本区域输出显示为带元素符号的列表