使用外键id连接2个表

时间:2013-08-09 15:53:55

标签: php mysql

我有一个2类系统,基本上我想做的是我有2个表,top_category和bottom_category,我创建了我的侧边栏,它将使用sql查询列出所有产品。有没有办法可以在一个SQL查询中提取top_category和bottom_category数据,并将bottom_category按top_category的外键id排序,这样当我将它们循环到列表中时,它们最终会出现在右边的嵌套中?

这是我的表格,

CREATE TABLE top_category (
  id INT PRIMARY KEY,
  NAME VARCHAR(100) 
);

CREATE TABLE bottom_category (
  id INT PRIMARY KEY,
  NAME VARCHAR(100) ,
  top_category_id INT REFERENCES top_category
);

这是我的产品表,所以当我点击bottom_category链接时,我希望它列出链接到bottom_category_id的产品:

create table product (
  id int primary key,
  name varchar(100) ,
  bottom_category_id int references bottom_category
);

2 个答案:

答案 0 :(得分:0)

你可以写点像

SELECT product.*, bottom_category.name, top_category.name
FROM product
LEFT JOIN bottom_category ON bottom_category.id = product.bottom_category_id 
LEFT JOIN top_category ON top_category.id = bottom_category.top_category_id
ORDER BY top_category.id,bottom_category.id

但是如果你有很大的表,那么就忘记第3个普通表格,并将类别的名称添加到产品表中。但是只有,如果你有真正的大类表。

<强> UPD 添加ORDER BY

答案 1 :(得分:0)

select p.*,
      bc.name bc_name,
      tc.name tc_name
from product p
left join bottom_category bc on p.bottom_category_id=bc.id
left join top_category tc on bc.top_category_id=tc.id
order by tc.id,bc.id