开发者

SELECT multiple tables with the same given id?

开发者 https://www.devze.com 2023-02-15 19:20 出处:网络
I\'m trying to select multiple tables and want to display them as if they belong together. I have 3 tables; users, profile and comment.

I'm trying to select multiple tables and want to display them as if they belong together. I have 3 tables; users, profile and comment.

The table users has the following rows; id, name, password.

profile; id, userid, bio, website.

comments; id, userid, comment, date.

The id of the users table is the same as the userid from pro开发者_运维技巧file and comments. I want to show all of the results, but ordered, so the comment and profile information from that user, are shown with that user, example;

Username: Mister Noname
Bio: 25 years old
Website: http://google.com
Comments: Bla bla bla!!

Username: Jay Wit
Bio: 99 years old
Website: http://stackoverflow.com
Comments: Best website ever!

I tried using JOIN, but can't seem to get it to work right, can someone help me out?

Thanks in advance.


Try something like this :

select *
from users
inner join profile on profile.userid = users.id
inner join comments on comments.userid = users.id
where users.id = $id
order by users.id

This will give you all the informations you need for each row (= user). If you need some help to access theses data from PHP, I can help too, just let me know.

The ordering is down by user id, but anything is possible, just ask.

Hope this helps.

Showing the data

Have a look at mysql_fetch_assoc, this part particularly :

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

$result is the result returned by mysql_query.


Try

SELECT u.name,p.bio,p.website,c.comment
FROM users u
JOIN profile p ON p.userid=u.id
JOIN comment c ON c.userid=u.id
ORDER BY u.id
0

精彩评论

暂无评论...
验证码 换一张
取 消