我想创建一个新闻更新系统,使用MySQL和PHP。但是我无法让它工作,在连接和 PHP 方面遇到问题,所以我可以显示新闻更新和附加的所有评论(如果有效用户登录,该人可以单独删除每条评论)。但这只是我遇到麻烦的 JOIN 语句。
我有这些表和数据库架构
- news_tbl(news_id、日期、用户(fk 到 users_tbl.用户名)、标题、正文和图片)
- users_tbl(用户名、电子邮件、密码、用户类型)
- comments_tbl(comments_id、姓名、注释news_id(fk 到 news_id))
我已经尝试过这个:
$sqlquery ="SELECT news_tbl.*, users_tbl.*, comments_tbl.*,
COUNT(comments_tbl.comments_id) AS comments_count
FROM news_tbl
LEFT JOIN users_tbl
ON news_tbl.user = users_tbl.username
LEFT JOIN comments_tbl
ON comments_tbl.news_id = news_tbl.news_id
GROUP BY news_tbl.news_id ";
但是我只能显示一条评论,我想要所有评论,并且我想添加每个评论的 ID,以便用户可以单独删除每个评论。而且,如果没有写评论,我也无法获得新闻ID?
这应该大致得到你想要的,尽管你应该始终分享你的查询,并准确指定你假装要实现的目标。
Select ut.user_id,nt.news_id,nt.headline, nt.body,ct.comments_id,
ct.comment,count(ct.comments_id) as total
from news_tbl nt
inner join users_tbl ut on ut.user_id=nt.user_id
left join comments_tbl ct on ct.news_id=nt.news_id
group by ut.user_id,nt.news_id
祝你好运。