Mysqli select from from two tables

三世轮回 提交于 2021-02-11 12:29:31

问题


I have data stored in two different tables called "posts" and "comments". Now i'm using two mysqli_query.

    $q = mysqli_query($db,"SELECT * FROM posts WHERE username='$username'");
    $q = mysqli_query($db,"SELECT * FROM comments WHERE username='$username'");

Can I make this with only one mysqli_query or with 3 tables?


回答1:


You can simply join both tables:

$q = mysqli_query($db,"SELECT * FROM posts 
LEFT JOIN comments ON comments.username=posts.username 
WHERE comments.username='$username'");

However, it looks like you are not using IDs. I suggest you to create ID auto-increment fields to make the relationship between tables. If you don't understand what I mean, try to follow a tutorial and in an our or two you would have learned more, than just by jumping into coding trying to do things and trying to understand how they work without even knowing if you are doing it right.



来源:https://stackoverflow.com/questions/36575695/mysqli-select-from-from-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!