添加两个表时复制结果

时间:2013-04-05 20:03:14

标签: php html mysql duplicates

我正在开设一个有类别的网站。当用户点击链接时,会转到categories.php?id=$id

这很有效。由于我使用FK,我必须使用此代码:

$result = mysql_query( "SELECT * FROM post_posts, post_cat WHERE post_cat = $id" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
if ($result) {
    while ($row = mysql_fetch_array($result)) {
        $_SESSION['idpost_posts']=$row['idpost_posts'];

        echo '<div id="single-post" class="slidingDiv">
            <div id="title">' . $row['post_header'] . '</div>
            <div id="image"><img src="' . $row['post_thumb'] . '" width="300" height="200"></div>
            <div id="text">' . substr($row['post_content'], 0, 500) . '<a href="page.php?id=' . $row['idpost_posts'] . '"> Les mer...</a>' . '      </div>
            <div id="author">' . "Skrevet: " . date('j. F Y ', strtotime($row['post_date'])) . ' | <a href="user.php?id=' . $row['idpost_users'] . '">' . $row['user_name'] . '</a></div> 
            <div id="post-divider"></div>
            </div>';
    }    
}

代码正在运行,但正如我之前所说,它显示了同一行5次。知道如何解决这个问题吗?

编辑: 这就是我现在使用的,它现在只显示两行,这更好:

$result = mysql_query( "SELECT DISTINCT idpost_posts, post_content, post_header, post_thumb, post_date, idpost_users, user_name FROM post_posts, post_cat, post_users WHERE post_cat = $id" )
        or die("SELECT Error: ".mysql_error());
        $num_rows = mysql_num_rows($result);if ($result) {while ($row = mysql_fetch_array($result)) {
        $_SESSION['idpost_posts']=$row['idpost_posts'];

        echo '<div id="single-post" class="slidingDiv">
            <div id="title">' . $row['post_header'] . '</div>
            <div id="image"><img src="' . $row['post_thumb'] . '" width="300" height="200"></div>
            <div id="text">' . substr($row['post_content'], 0, 500) . '<a href="page.php?id=' . $row['idpost_posts'] . '"> Les mer...</a>' . '      </div>
            <div id="author">' . "Skrevet: " . date('j. F Y ', strtotime($row['post_date'])) . ' | <a href="user.php?id=' . $row['idpost_users'] . '">' . $row['user_name'] . '</a></div> 
            <div id="post-divider"></div>
            </div>';

2 个答案:

答案 0 :(得分:1)

改变这个  `

   $result = mysql_query( "SELECT * FROM post_posts, post_cat WHERE post_cat = $id" )

`对此:

$result = mysql_query( "SELECT DISTINCT * FROM post_posts, post_cat WHERE post_cat = $id" )

答案 1 :(得分:0)

你的SQL“SELECT * FROM post_posts,post_cat WHERE post_cat = $ id”正在post_posts和post_cat表之间执行交叉笛卡尔联接(你不想这样)。您应该定义哪些列应该像这样一起加入两个表。

SELECT * FROM post_posts, post_cat WHERE post_posts.<primary key col name> = post_cat.<foreign key col name> AND post_cat = $id

你要替换&lt;&gt;使用在每个表中定义外键关系的列。如果您需要更详细的帮助,您需要发布外键约束详细信息,包括它应用于的列以及它在另一个表中引用的列。