6

MySQL left join 后面的查询条件未生效呢

 2 years ago
source link: https://www.oschina.net/question/1175066_2324780
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

MySQL left join 后面的查询条件未生效呢

zgw06629 发布于 昨天 11:22
阅读 174

有这么一个主表 保存了各种类型的数据 如 企业 人物 文章  

create table entry_data(id int primary key, name varchar(50), type varchar(20));
insert into entry_data select 1, '公司一', 'company';
insert into entry_data select 2, '公司二', 'company';
insert into entry_data select 3, '张三', 'people';
insert into entry_data select 4, '李四', 'people';
insert into entry_data select 5, '文章一', 'article';
insert into entry_data select 6, '文章二', 'article';

mysql> select * from entry_data;
+----+-----------+---------+
| id | name      | type    |
+----+-----------+---------+
|  1 | 公司一    | company |
|  2 | 公司二    | company |
|  3 | 张三      | people  |
|  4 | 李四      | people  |
|  5 | 文章一    | article |
|  6 | 文章二    | article |
+----+-----------+---------+

同时 有另外一个关联关系表 不同类型之间可以互相关联 如 企业关联文章  人物关联文章

create table entry_relation(entry_id1 int,entry_id2 int, entry_type1 varchar(20), entry_type2 varchar(20));

insert into entry_relation select 1,5,'company','article';
insert into entry_relation select 2,5,'company','article';
insert into entry_relation select 2,6,'company','article';
insert into entry_relation select 3,6,'people','article';
insert into entry_relation select 5,4,'article','people';


mysql> select * from entry_relation;
+-----------+-----------+-------------+-------------+
| entry_id1 | entry_id2 | entry_type1 | entry_type2 |
+-----------+-----------+-------------+-------------+
|         1 |         5 | company     | article     |
|         2 |         5 | company     | article     |
|         2 |         6 | company     | article     |
|         3 |         6 | people      | article     |
|         5 |         4 | article     | people      |
+-----------+-----------+-------------+-------------+

当想查询哪些关联表中的公司已不在主表中了 即从主表中删除了 但是没有删除关联表 查询的结果 与我想的不一致呢

mysql> select r.entry_id1, r.entry_type1, d.id from entry_relation r left join entry_data d on r.entry_id1 = d.id and r.entry_type1 = 'company' where d.id is null;
+-----------+-------------+------+
| entry_id1 | entry_type1 | id   |
+-----------+-------------+------+
|         3 | people      | NULL |
|         5 | article     | NULL |
+-----------+-------------+------+

明明都指定了 entry_type1 怎么不生效呢?

注: 数据库用的是MySQL


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK