fetch multiple tables in one query

人走茶凉 提交于 2019-12-02 14:23:17

问题


This is thirty post in one houre . so i am sorry !

but i did't get what i want !

i will try to explain more ..

i have two tables ..

POSTS <-- my ( all site posts ) COMMENTS <-- my ( all site comments )

i want display all POSTS and COMMENTS in this one page

buy ( 1 query )

i have in POSTS table (100 post) and i have in COMMENTS table ( 20 comment )

i try this code

$qq = mysql_query("SELECT posts.*,comments.* 
FROM posts LEFT JOIN comments 
ON posts.post_id = comments.post_id");
    while($tt = mysql_fetch_array($qq)){
    echo $tt['comment_title'] . '<br />'; //the title of comments !
}

in above , iam trying to print comment title

i said above i have ( 20 comments ) only !

the code is output ( 120 comments with repeat ! )

120 is the total of the two tables !

/* i want only print the 20 comments and the 100 post ( in one query )

How i can do that ! ?

in the end i am sorry for this more question

but i am really need help ! my site is down


回答1:


Your question is super ambiguous, so I will do my best:

SELECT * FROM posts LEFT JOIN comments ON posts.post_id = comments.post_id

That is the query you want (same that you have, but * instead of "posts.,comments.".

This will, of course, retrieve all the rows in Posts, even if they don't have any comments. You need to do:

SELECT * FROM posts LEFT JOIN comments ON posts.post_id = comments.post_id WHERE posts.post_id= = <some_id>

to get only a specific post's comments. Of course, that would be silly since it would be the same thing as just doing:

SELECT * FROM comments WHERE post_id = <some_id>

If you want to only select rows in Posts that have comments, you must do:

SELECT * FROM posts INNER JOIN comments ON posts.post_id = comments.post_id

Or

SELECT * FROM posts NATURAL JOIN comments

(they have the same effect)




回答2:


I am assuming you need to get all posts (and by posts you mean articles)

yes, you can use one query:

SELECT * FROM articles;

To get all articles




回答3:


<?php
$sql = "SELECT * FROM articles";
$query = mysql_query($sql);
while($result = mysql_fetch_assoc($query){
    echo $result['post_title'];
}
?>


来源:https://stackoverflow.com/questions/6825736/fetch-multiple-tables-in-one-query

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