mysql Selecting from two different tables.

后端 未结 9 776
终归单人心
终归单人心 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 06:05

    You can use table name to select the columns. Ex:

    $Query = "select table1.body, table1.stamp, users.username from posts, users where user_id = '$userid' order by stamp desc";
    

    But, this method is not good in performance.

    The best method is:

    $Query = "SELECT table1.body, table1.stamp, users.username 
    FROM posts 
    INNER/LEFT/RIGHT JOIN users 
    ON users.user_id = '$userid' AND users.user_stamp = stamp.stamp_id
    

    All the tables must be related.

    Greetings,

    0 讨论(0)
  • 2021-01-28 06:05
    $sql = "select body, stamp from posts , username from users where user_id = '$userid' order by stamp desc";
    

    I just corrected the syntactical error in your query... that is the AND keyword should be replaced by ,.

    0 讨论(0)
  • 2021-01-28 06:06
    $sql = "SELECT p.body,p.stamp,u.username from posts p LEFT JOIN users as u ON (p.user_id = u.user_id) WHERE user_id = '$user_id' ORDER BY p.stamp DESC";
    

    should do it

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