日期:2014-05-16  浏览次数:20795 次

2个表完全相同,查找b表的每条记录是不是在a表中匹配怎么做?
2个表,一个是access表,一个sale表,id(自动编号)   ,a,b,c   ,都是int型,起始时间(btime),结束时间(etime);

需要给sale表作查询,如果sale表的一条记录的   a   b   c三个字段能全部和access的某条记录匹配,并且起始和结束时间也在access表的2个时间范围之内就返回   id号,yes   否则返回   id号,   no  

匹配条件A.a=B.a   and   A.b=B.b   and   A.c=B.c   and   A.btime <   B.btime   and   A.etime> B.etime  
最后返回就是   2个字段,一个sale表的id号,一个是yes/no
差不多就是这个意思吧,以前好像写过,2年多没写sql语句了,全忘记了   大家帮帮忙


------解决方案--------------------
先select id,加上你上面的条件,然后用not in

select * from tba where id not in (select id from tbb where #$@$#@*^$#)
------解决方案--------------------
mysql> select * from a;
+----+------+------+------+-------+-------+
| id | a | b | c | time1 | time2 |
+----+------+------+------+-------+-------+
| 1 | 1 | 2 | 3 | 10 | 20 |
| 2 | 2 | 3 | 4 | 15 | 25 |
| 3 | 3 | 4 | 5 | 20 | 30 |
+----+------+------+------+-------+-------+
3 rows in set (0.00 sec)

mysql> select * from b;
+----+------+------+------+-------+-------+
| id | a | b | c | time1 | time2 |
+----+------+------+------+-------+-------+
| 1 | 1 | 2 | 3 | 11 | 19 |
| 2 | 2 | 3 | 4 | 15 | 25 |
| 3 | 3 | 4 | 5 | 20 | 30 |
+----+------+------+------+-------+-------+
3 rows in set (0.00 sec)

mysql> SELECT a.id,
-> IF(b.id, 'yes ', 'no ')
-> FROM a
-> LEFT JOIN b
-> ON b.time1 > a.time1
-> && b.time2 < a.time2
-> && a.a = b.a
-> && a.b = b.b
-> && a.c = b.c;
+----+-----------------------+
| id | IF(b.id, 'yes ', 'no ') |
+----+-----------------------+
| 1 | yes |
| 2 | no |
| 3 | no |
+----+-----------------------+
3 rows in set (0.00 sec)
------解决方案--------------------
楼上正解
------解决方案--------------------
学习。