mysql Selecting from two different tables.

后端 未结 9 775
终归单人心
终归单人心 2021-01-28 05:01
$sql = \"select body, stamp from posts where user_id = \'$userid\' order by stamp desc\";

NOTE: the above query works fine. What I want to do is also s

相关标签:
9条回答
  • 2021-01-28 05:41

    You'll need to use a JOIN to bring the two tables together on the matching field, so something like:

    $sql = "SELECT p.body, p.stamp, u.username FROM posts p INNER JOIN users u ON p.user_id=u.user_id WHERE p.user_id='$userid' ORDER BY p.stamp DESC";
    
    0 讨论(0)
  • 2021-01-28 05:42
    $sql = "
    select body, stamp from posts where user_id = '$userid' order by stamp desc
    UNION ALL
    select body, stamp from username where user_id = '$userid' order by stamp desc
    ";
    

    http://dev.mysql.com/doc/refman/5.0/en/union.html

    0 讨论(0)
  • 2021-01-28 05:49

    Try this:

    select body, stamp, username 
    from posts p JOIN users a ON p.user_id = a.user_id 
    WHERE p.user_id = '$userid' order by stamp desc
    
    0 讨论(0)
  • 2021-01-28 05:59
     select body, stamp, username 
        from posts,users 
        where users.user_id = post.user_id 
            and users.user_id = '$userid' 
        order by stamp desc;
    
    0 讨论(0)
  • 2021-01-28 06:02

    You should use aliases or table name to avoid the duplicate problem like this

    tablename.column
    

    or

    alias.column
    

    you can set the alias in your where clause :

    FROM table as alias_name
    
    0 讨论(0)
  • 2021-01-28 06:04

    This should work fine:

    SELECT posts.body, posts.stamp, users.username 
    FROM posts, users 
    WHERE posts.user_id = '$userid' AND posts.user_id = users.user_id
    ORDER BY posts.stamp DESC
    
    0 讨论(0)
提交回复
热议问题