我有一个问题。这是我的数据库结构
**company**
id | name
---------
1, Test
2, demo
**address**
id | name
---------
1, test1
2, test2
3, bla6
**address_company**
id | address_id | company_id
1, 1, 1
2, 2, 1
3, 3, 2
我的疑问是:
SELECT company.name, address.name FROM company
INNER JOIN address_company on address_company.company_id = company.id
INNER JOIN address on address.id = address_company.address_id
这很有效。但我需要过滤结果。
所以当人们点击地址(前端):test1时,它只需要显示公司:测试
我可以这样做:
WHERE address.name = "test1"
这也有效但我需要进一步过滤,所以我需要的是
WHERE address.name = "test1" AND address.name = "test2"
但是这不起作用,它没有显示结果。我只能过滤1个地址,我需要过滤更多地址。
希望你们能理解我并能帮助我。 谢谢!
答案 0 :(得分:1)
使用OR代替和,或使用in()结构:
WHERE address.name = 'test1' OR address.name = 'test2'
WHERE address.name IN('test1', 'test2' )
注意:我希望以下连接条件在问题中输入错误:
INNER JOIN address on address.id = address_company.id
答案 1 :(得分:1)
以下策略倾向于unique key(address_id,company_id)
,确保该组合级别没有重复
create table company
( id int auto_increment primary key,
name varchar(100) not null
);
insert company(name) values ('Test'),('demo');
create table address
( id int auto_increment primary key,
name varchar(100) not null
);
insert address(name) values ('test1'),('test2'),('bla6');
create table address_company
( id int auto_increment primary key,
address_id int not null,
company_id int not null,
unique key(address_id,company_id) -- no dupes allowed ! I am banking on this below
);
insert address_company(address_id,company_id) values (1,1),(2,1),(3,2);
select company_id,count(*) theCount from address_company
where address_id in (1,2)
group by company_id having theCount>1;
+------------+----------+
| company_id | theCount |
+------------+----------+
| 1 | 2 |
+------------+----------+
select company_id,count(*) theCount from address_company
where address_id in (select id from address where name in ('test1','test2'))
group by company_id having theCount>1;
+------------+----------+
| company_id | theCount |
+------------+----------+
| 1 | 2 |
+------------+----------+
因此,如果该组的/返回大于1的计数,我实际上是在name1和name2之后,那么我知道该行符合条件。然后那一行当然有name1 和 name2。
回到独特的关键部分:这可以确保我们不会被公司拥有两次相同的地址。哪个首先没有意义,这也会搞乱这个策略。
显然,架构需要一些索引帮助,而FK并不会打破任何人的心。但这只是一个稻草人。