[英]MySQL INNER JOIN two tables where one table contains multiple rows with same id
I want to get id's from one table depending on multiple rows from another table with same id. 我想从一个表中获取ID,具体取决于另一个表中具有相同ID的行。 The id's has to only be returned if all rows from the other table matches each row request.
仅当另一个表中的所有行均与每个行请求匹配时,才必须返回ID。 My table structure looks like this.
我的表结构如下所示。
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
I have tried with INNER JOIN, but i can't seem to make it work no matter how i try. 我已经尝试使用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' )
Can anybody answer me what i'm doing wrong with my query? 有人可以回答我我的查询问题吗? Thank you :)
谢谢 :)
Hmm.. try this:- 嗯..试试这个:-
/*
drop table tbl_one;
drop table tbl_two;
create table tbl_one(id int, companyName varchar(20)) ;
Insert into tbl_one values
(1, 'CompanyOne'),
(2, 'CompanyTwo') ;
create table tbl_two(id int,type varchar(20), content varchar(20));
insert into tbl_two values
(1 , 'zipcode' , '54321'),
(1 , 'category' , 'Car dealers'),
(2 , 'zipcode' , '54321'),
(2 , 'category' , 'Supermarkets');
*/
SELECT t1.*
FROM tbl_one t1
WHERE t1.id in (select t2.id from tbl_two t2 where t2.id = t1.id and t2.type = 'zipcode' AND t2.content = '54321')
and t1.id in (select t3.id from tbl_two t3 where t3.id = t1.id and t3.type = 'category' AND t3.content = 'Car dealers')
The query you provided doesn't work because tbl_two.type cannot equal "zipcode" and "category" at the same time. 您提供的查询不起作用,因为tbl_two.type不能同时等于“邮政编码”和“类别”。 Perhaps this is what you meant?
也许这就是你的意思? Note the
OR
operator on line 7, as opposed to your use of AND
... 请注意第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"
OR perhaps you want to find all of the car dealers in 54321, in which case you would need two joins... 或者,也许您想在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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.