如何正确地做INNER JOIN ?mysql


How to do INNER JOIN correctly ? mysql

我有两个表:

table1:

businessessid | businessName | categoryId

   1              name1        355
   2              name2        451
   .                .           .    
   .                .           .         

表二:

categoryId | bussinessId

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中的业务之间的关系?

我知道categoryId colat table1应该迁移到table2,但现在我不能这样做?

实际上我也尝试了这个查询:

SELECT table1.businessName FROM table1 INNER JOIN table2
WHERE
(table2.businessId = table1.businessId AND tabl2.categoryId = $_GET['categoryId'])
OR table1.businessId = $_GET['categoryId' ;

但是这不能很好地工作!

将连接条件放在on子句中通常更简洁。如果您有多个连接条件(业务和类别id),您可以使用and同时拥有它们:

SELECT     table1.businessName 
FROM       table1 t1
INNER JOIN table2 AS t2 ON t2.businessId = t1.businessId AND 
                           t2.categoryId = t1.categoryId
WHERE      t2.categoryId = $_GET['categoryId'];

尝试如下,因此首先使用公共键连接表,然后使用where

过滤出数据
SELECT 
table1.businessName FROM table1 
INNER JOIN table2 on table2.businessId = table1.businessId
where 
table2.categoryId = $_GET['categoryId'] ;

(未经测试)此查询还显示了table1中 CC__4与businessId之间关系的数据。我选择了UNION,因为我认为在table1中,类别和业务之间的联系是可能的不包含在table2

select businessName
from table1
where categoryId = $_GET['categoryId']
UNION ALL
select t1.businessName
from table1 as t1
inner join table2 as t2 on t2.categoryId = t1.categoryId AND
               t2.businessId = t1.businessId
where t2.categoryId = $_GET['categoryId']