MySQL的新知识:
之前数据库没学好,不知道LEFT JOIN ON后边可以加条件
首先业务是有个A表,然后会依据A表信息来在B表生成一条对应数据,
操作时候展示A表数据,如果B表已经有对应数据,显示数据,如果没有,则可以新增数据。
B表中有保存A表的ID。
SELECT a.id AS "a.id", a.CODE AS "a.code", b.id AS "b.id", b.CODE AS "b.code", b.a_id AS "b.aID" FROM a LEFT JOIN b ON b.a_id = a.id
查询结果:
现在要求是要B的数据下游会操作,如果数据有问题就会作废掉,这里就用code来标识,当code为1时,就说明这条数据是作废的。
在上游的显示中,就是A依然有数据,但B为空。
最开始在where条件中写,SQL:
SELECT a.id AS "a.id", a.CODE AS "a.code", b.id AS "b.id", b.CODE AS "b.code", b.a_id AS "b.aID" FROM a LEFT JOIN b ON b.a_id = a.id WHERE b.CODE = ‘0‘
查询结果:
很明显就数据丢了一条,达不到目的,突然间一个思路,where条件能否放到LEFT JOIN ON的后边,试了一下,效果有了:
SELECT a.id AS "a.id", a.CODE AS "a.code", b.id AS "b.id", b.CODE AS "b.code", b.a_id AS "b.aID" FROM a LEFT JOIN b ON b.a_id = a.id AND b.CODE = ‘0‘
查询结果:
还是第一次意识到LEFT JOIN ON后边的条件可以用AND来实现多个
原文地址:https://www.cnblogs.com/JillisRealM/p/11994502.html
时间: 2024-10-08 21:23:24