【发布时间】:2014-06-20 09:07:49
【问题描述】:
我有两张桌子:
表 1:
企业标识 |企业名称 |类别ID
1 name1 355
2 name2 451
. . .
. . .
表2:
类别 ID |业务标识
56 2
99 2
100 8
. .
. .
因此业务可能属于多个类别(一对多关系)。
我想通过 categoryId 获取商家名称。 我正在使用这个查询:
SELECT table1.businessName FROM table1 INNER JOIN table2
WHERE
table2.businessId = table1.businessId AND table2.categoryId = $_GET['categoryId'];
这个查询只是根据table2获取属于特定categoryId的业务,而忽略table1的关系。
如何改进查询以检查 categoryId 和 table1 上的业务之间的关系?
我知道 table1 的 categoryId col 应该迁移到 table2 ,但现在我不能这样做?
其实我也试过这个查询:
SELECT table1.businessName FROM table1 INNER JOIN table2
WHERE
(table2.businessId = table1.businessId AND tabl2.categoryId = $_GET['categoryId'])
OR table1.businessId = $_GET['categoryId' ;
但这并不好用!它带来了很多行!
【问题讨论】:
-
看来你的意思是多对多。否则,一个类别只能有一个业务。为什么table1中有categoryId?
-
1) 你缺少
on声明; 2)如果你有这种类型的表,那么制作一个视图,将所有相关表中的信息加入数据库; 3)我会说,对于这种类型的工作,你最好使用存储过程(避免使用 mysql injectionio[get statement]) -
@marek 不,这不是多对多!这是设计上的错误! (我将关系分开),所以 table1 处的 businessId 是 primaryKey !我现在不能改变设计! " 知道 table1 的 categoryId col 应该迁移到 table2 ,但现在我不能这样做?"
-
@user3648409 "业务可能属于多个类别" + 1toM 关系 => 类别只能有一个业务。那并不能使它成为一个类别。