【问题标题】:How to do INNER JOIN correctly ? mysql如何正确地进行 INNER JOIN ? mysql
【发布时间】: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 关系 => 类别只能有一个业务。那并不能使它成为一个类别。

标签: php mysql sql


【解决方案1】:

on 子句中加入连接条件通常更简洁。如果您有多个加入条件(业务 ID 和类别 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'];

【讨论】:

    【解决方案2】:

    尝试如下,首先用公共键连接表,然后使用where过滤掉数据

    SELECT 
    table1.businessName FROM table1 
    INNER JOIN table2 on table2.businessId = table1.businessId
    where 
    table2.categoryId = $_GET['categoryId'] ;
    

    【讨论】:

      【解决方案3】:

      (未经测试)此查询还显示categoryIdtable1businessId 的关系数据。 我选择了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']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 2010-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多