MySQL INNER JOIN两个表,其中一个表包含多个具有相同id的行

时间:2016-06-29 15:33:59

标签: mysql join

我希望从一个表中获取id,这取决于具有相同id的另一个表中的多行。只有当另一个表中的所有行都匹配每个行请求时,才必须返回id。我的表结构看起来像这样。

   
tbl_one 
------------------  
id  companyName 
------------------
1   CompanyOne  
2   CompanyTwo  

tbl_two 
-----------------------------   
id  type        content
-----------------------------
1   zipcode     54321
1   category    Car dealers
2   zipcode     54321
2   category    Supermarkets

我已尝试使用INNER JOIN,但无论我如何尝试,我似乎都无法工作。

SELECT 
    tbl_one.id FROM tbl_one 
INNER JOIN 
    tbl_two
ON
    tbl_two.id = tbl_one.id 
WHERE
( 
    type = 'zipcode' AND content = '54321'
) 
  AND
( 
    type = 'category' AND content = 'Car dealers' 
)

有人可以回答我我的查询错误吗? 谢谢:))

2 个答案:

答案 0 :(得分:2)

嗯..试试这个: -

export interface tool {
    type: string;
    name: string;
    draw(context:any): void;
}

class textTool implements tool {
    type:string = 'textTool';
    name:string;
    fontSize:number;
    fontType:string;

    draw(context:any):void {
    }
}

const typeMapping:any = {
    'textTool' : textTool
    //all other types
};
let json = '[{"type":"textTool", "name": "someName", "fontSize": 11}]';
let elements: Array<tool> = JSON.parse(json).map((i:any) => {
    let target:any = new typeMapping[i.type];
    for (const key in i) {
        target[key] = i[key];
    }
    return target;
});

答案 1 :(得分:1)

您提供的查询不起作用,因为tbl_two.type不能同时等于“zipcode”和“category”。 Perhaps this is what you meant?请注意第7行的OR运算符,而不是使用AND ...

SELECT one.id
FROM tbl_one one
JOIN tbl_two two
ON   two.id = one.id
WHERE
     two.type = "zipcode" AND two.content = "54321"
OR   two.type = "category" AND two.content = "car dealers"

或许你想找到54321的所有汽车经销商,在这种情况下你需要两个连接......

SELECT one.id
FROM tbl_one one
JOIN tbl_two one_zip
ON   one_zip.id = one.id
AND  one_zip.type = "zipcode"
AND  one_zip.content = "54321"
JOIN tbl_two one_cat
ON   one_cat.id = one.id
AND  one_cat.type = "category"
AND  one_cat.content = "car dealers"