我的 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/