构建查询以根据另一个表选择数据

时间:2014-01-08 23:31:55

标签: html mysql mysqli

enter image description here

示例数据

wall_id   wall_name
  1        wall_1
  2        wall_2
  6        wall_6

wall_categories

wall_id   category_id
  1           2
  2           1
  6           1
  6           2

类别

category_id  category_name
  1            Wallpaper
  2            Photography

HTML

<a href="file.php?category=wallpaper">Wallpaper</a>
<a href="file.php?category=photography">Photography</a>

我需要做的是,当用户点击Wallpaper链接时,我希望将wallpaper类别的图片显示为photography。我已经构建了一个初始查询但是它生成了重复记录,因为我使用了join,必须添加其他东西以使其工作。

    SELECT DISTINCT walls.wall_id, walls.wall_name, walls.wall_views, walls.upload_date,
 categories.category_name FROM categories INNER JOIN wall_categories ON 
wall_categories.category_id=categories.category_id INNER JOIN walls ON 
walls.wall_id=wall_categories.wall_id;

或由于category_id已修复,我们只能使用wallswall_categories表。然后让我们来吧说我们可以使用以下html。

<a href="file.php?category=1">Wallpaper</a>
<a href="file.php?category=2">Photography</a>

1 个答案:

答案 0 :(得分:1)

您不是按category_id限制查询,因此它会返回所有具有相关类别的挂壁记录。

SELECT DISTINCT walls.wall_id, walls.wall_name, walls.wall_views, walls.upload_date,
 categories.category_name FROM categories INNER JOIN wall_categories ON 
wall_categories.category_id=categories.category_id INNER JOIN walls ON 
walls.wall_id=wall_categories.wall_id
WHERE category.category_id = ?
;

然后将?绑定到用户选择的相应类别ID。