问题
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