fetch multiple tables in one query

前端 未结 3 1334
北海茫月
北海茫月 2021-01-28 10:53

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

相关标签:
3条回答
  • 2021-01-28 10:57
    <?php
    $sql = "SELECT * FROM articles";
    $query = mysql_query($sql);
    while($result = mysql_fetch_assoc($query){
        echo $result['post_title'];
    }
    ?>
    
    0 讨论(0)
  • 2021-01-28 11:01

    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)

    0 讨论(0)
  • 2021-01-28 11:18

    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

    0 讨论(0)
提交回复
热议问题