mysql 显示公司的所有其他结果

mysql show all other results from company

我有一个问题。这是我的数据库结构

**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时,它只需要显示公司:Test

我能做到:

WHERE address.name = "test1"

这也有效,但我需要进一步过滤,所以我需要的是

WHERE address.name = "test1" AND address.name = "test2" 

但这不起作用,它不显示结果。我只能过滤 1 个地址,我需要过滤更多地址。

希望大家能理解我,帮助我。 谢谢!

使用 OR 代替 and,或者使用 in() 结构:

WHERE address.name = 'test1' OR address.name = 'test2'


WHERE address.name IN('test1', 'test2' )

注意:我希望以下连接条件只是在问题中输入错误:

 INNER JOIN address on address.id = address_company.id

以下策略依靠 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 |
+------------+----------+

因此,如果分组依据 / 的 returns 大于 1 的计数,我实际上是在 name1 和 name2 之后,那么我知道该行符合条件。那一行当然有 name1 and name2.

回到独特的关键部分:这可以确保我们不会被欺骗两次拥有相同地址的公司。哪个首先没有意义,而且会搞乱这个策略。

显然,该架构需要一些索引帮助,FK 不会伤到任何人的心。但这只是一个稻草人。