在MySQL中选择两个表

时间:2014-03-06 12:17:35

标签: mysql select

我有两张表hitsposts。在hits表格中我有id_post,hitsposts表格id,title

我需要使用相关匹配和按命令排序的所有帖子构建报告。任何人都可以帮我选择吗?

3 个答案:

答案 0 :(得分:2)

SELECT   posts.id as id, posts.title as title, hits.hits as hitsdate
FROM     posts INNER JOIN hits ON hits.id_post = posts.id
ORDER BY hits.hits

答案 1 :(得分:0)

SELECT   posts.id, posts.title, hits.hits
FROM     posts LEFT JOIN hits ON hits.id_post = posts.id
ORDER BY hits.hits

答案 2 :(得分:0)

试试这个

$q=mysql_query("SELECT * FROM `posts` ORDER BY `title`;");
while($qresult=mysql_fetch_array($q))
{
    $post_id=$qresult['id'];
    $post_title=$qresult['title'];
    $hitsretreiver=mysql_query("SELECT * FROM `hits` WHERE `id_post`='$post_id';")
    while($hitsretreiverresult=mysql_fetch_array($hitsretreiver)
    {
         $relatd_hit=$hitsretreiverresult['hits'];
         echo $post_title;
         echo $relatd_hit;
    }
 }

在此代码中,您获得表格帖子中的每条记录,并从表格匹配中获取具有相同ID的记录