我的数据库中有一个名为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/