[英]PHP mysql how to join two tables to link name from one table and post from other table
所以我现在非常糟糕,我现在有这个代码
$test = "SELECT `status`,`pubdate` FROM `status` ORDER BY `pubdate` DESC";
$stmt = $db->prepare($test);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<section class='statusar'>"."<article>";
echo $row['status'];
echo $row['pubdate'];
echo "</article></section>";
}
它显示了帖子,但现在我想从另一个表中获取用户的名字并用帖子显示它。 我该怎么做?
这两个表我看起来像这样
这是帖子的表格
Status_id int unsigned auto_increment primary
user_id int unsigned index
status varchar(600)
pubdate datetime
这是另一张桌子
user_id int unsigned auto_increment primary index
firstname varchar(30)
surname varchar(30)
username varchar(30) unique
password varchar(90)
我这样做了,他们在user_ids之间有一个关系
编辑
我想我已经明白了,因为它现在有效:D所以我现在使用的时候
SELECT status, pubdate,firstname,surname FROM status INNER JOIN user ON status.user_id = user.user_id ORDER BY status.pubdate DESC
它显示了我想要的所有东西,我也试过了
SELECT * FROM status INNER JOIN user ON status.user_id = user.user_id ORDER BY status.pubdate DESC";
这也有效,感谢帮助人:D
只需使用inner join
:
SELECT s.status, s.pubdate, u.firstname
FROM status s
INNER JOIN usertable u ON s.user_id = u.user_id
ORDER BY s.pubdate DESC
这假设user_id
存在于usertable
。 如果情况可能不是这样,那么您可能希望使用outer join
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.