使用left join即可。table1中不存在于table2中的user_id在table2的user_id字段将会是null,然后对table2的user_id字段过滤以下即可。具体sql语句如下:select a.user_id,b.user_id as temp from table1 a left join table2 b on a.user_id=b.user_id and b.b_id=20 having temp is null
调试欢乐多
select a.user_id,b.user_id as temp #选取两个表中的user_id
from table1 a left join table2 b # LEFT JOIN是什么意义呢?属于基础知识
on a.user_id=b.user_id # 最简单的联合查询条件
and b.b_id=020 # 只需要020下面的user_id
having temp is null # 将left join后的结果过滤一下,去掉table2中非null(也就是user_id存在于table2的行)
from table2
left join table1 on table2.user_id=table1.user_id
where table2.b_id=020 and table1.user_id is null
的是正解那么楼主为什么不用not in呢?
讲起速度和效果来差不多的啊
后来我用两条查询来实现的,大意如下:
select user_id from table2 where b_id=020
得出数组A,user_id数符串str;
select user_id from table1 where user_id in (str)
得出数组B
$result = array_diff (A, B);是我要得到的数据。说明下,数组A最多是200个user_id左右,所以第二条查询可能快点。
但也没有真正比较查询时间,希望大家继续讨论下,能否有更好的解决方法。
所以除非不得已,还是少用的好
不过楼主说"不管是左联还是内联,都会出现数据库",那么你给某些字段加过索引吗
b_id和user_id的多列索引