联合查询
2个表
test1 test2 结构一致
只有一个left join 只有一个条件 关联 (随机组合得到了多一倍的数据)
正常关联2个主键
正常的数据查询结果
查询结果多了一倍
结论 : 如果联合主键不放到on后面, 证明随机组合的时候只用了其中一个键另一个键没有受约束,
Mysql 先联合再where 数据导致。
测试数据可以根据sql进行验证
select * from test1 a left join test2 b on a.id= b.id where a.id=1 and b.id=1
select * from test1 a left join test2 b on a.id= b.id and a.id1=b.id1 where a.id=1
DROP TABLE IF EXISTS test1
;
CREATE TABLE test1
(
id
int(11) NOT NULL,
id1
int(255) NOT NULL,
PRIMARY KEY (id
,id1
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
– Records of test1
INSERT INTO test1
VALUES (‘1’, ‘1’);
INSERT INTO test1
VALUES (‘1’, ‘2’);
INSERT INTO test1
VALUES (‘2’, ‘1’);
INSERT INTO test1
VALUES (‘2’, ‘2’);
DROP TABLE IF EXISTS test2
;
CREATE TABLE test2
(
id
int(11) NOT NULL,
id1
int(255) NOT NULL,
PRIMARY KEY (id
,id1
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
– Records of test2
INSERT INTO test2
VALUES (‘1’, ‘1’);
INSERT INTO test2
VALUES (‘1’, ‘2’);
INSERT INTO test2
VALUES (‘2’, ‘1’);
INSERT INTO test2
VALUES (‘2’, ‘2’);