如何从链接表中获取类别链接,其中一个表中的类别与另一个表中的链接匹配“

时间:2012-03-07 01:24:54

标签: mysql

我是编程新手并且碰壁了。我正在尝试构建一个简单的链接网站作为学习mysql和php的起点。

我有两个表:类别 - 链接

在类别表中,我有35个类别的列表。 id(int)自动增量主键和类别varchul

在链接中,我有id(int)自动增量主键,链接名称,URL和描述。

我已经达到了这样的程度,我可以使用类别列出类别并为每个类别创建一个URL?id = $ id。但是我无法获得与类别相关联的链接以按类别显示。我要么获得所有链接,要么没有链接。我使用了join,left join,right join,其中links.categories = categories.categories。什么都行不通。这是获取类别的代码,我只是不知道如何获取每只猫的链接。任何人都可以指出我正确的方向。

enter code here
    <? include "db.php" ?>
    <?php
    $id = intval($_GET['id']); // force user input to an int
    if(!empty($id)) // if the user input is not empty or 0
    {
    $query = "SELECT * FROM categories WHERE id =  $id  LIMIT 1"; // attempt to select the row for the given id
    $result = mysql_query($query) or die(mysql_error());

    if(mysql_num_rows($result) > 0) // if the categorie was found
    {
    $row = mysql_fetch_assoc($result); // fetch the resultset to an array called $row

    echo $row['categories']; // echo the categories field from the row
    // etc.
    }
    else
    {
    die('Error: Bad ID'); // the categories was not found
    }
    }
    else
    {
    die('Error: Bad ID'); // the id given was not valid
    }
    mysql_close();
    ?>

我希望有人可以提供帮助。提前致谢

1 个答案:

答案 0 :(得分:0)

您的设计中的类别和链接之间没有任何关系,这就是您没有获得任何数据的原因。

  1. 如果每个链接只能属于一个类别,则将categoryid字段添加到链接表中,然后在链接和类别之间加入时使用该字段。

  2. 如果每个链接可以属于多个类别,那么您需要一个带有categoryid和linkid列的categorylinks表,这两个列都是防止同一个链接多次分配到同一类别的主键。然后您可以使用此表

  3. 加入