MySQL INNER JOIN查询多个匹配项,除非

时间:2014-01-08 16:46:57

标签: mysql sql

我有一张看起来像这样的表:

tableid memberid    date
1       +123456     2013-12-04 9:00:00
1       9876        2013-12-04 10:44:00
1       8765        2013-12-04 11:15:00
1       6900        2013-12-04 12:20:00
1       7654        2013-12-04 15:20:00
1       6250        2013-12-04 15:20:00
1       5655        2013-12-04 15:25:00
2       +145879     2013-12-04 15:50:00
2       5668        2013-12-04 16:12:00
2       3654        2013-12-04 17:25:00 
2       6250        2013-12-04 19:02:00
2       3447        2013-12-04 19:33:00

我使用以下查询获取多个匹配项:

SELECT *
FROM connector AS c1
INNER JOIN connector AS c2 ON c1.tableid=c2.tableid
INNER JOIN connector AS c3 ON c1.tableid=c3.tableid

WHERE
    (c1.memberid LIKE '+1%')
    AND (c2.memberID LIKE '56%')
    AND (c3.memberID = 6250)
    AND  c2.date BETWEEN '2013-12-04 0:00:00' and '2013-12-04 23:59:59'

这最初起作用,上面的代码输出如下:

tableid memberid    date                    tableid     memberid    date                    tableid memberid    date
1       +123456     2013-12-04 9:00:00      1           5655        2013-12-04 15:25:00     1       6250        2013-12-04 15:20:00
2       +145879     2013-12-04 15:50:00     2           5668        2013-12-04 16:12:00     2       6250        2013-12-04 19:02:00

我需要的是省略包含tableid memberid的{​​{1}}个6900组。

因此输出应该只有以下内容:

tableid memberid    date                tableid memberid    date                tableid memberid    date
2       +145879     2013-12-04 15:50:00 2       5668        2013-12-04 16:12:00 2       6250        2013-12-04 19:02:00

由于tableid 16900列中有memberid

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM connector AS c1
INNER JOIN connector AS c2 ON c1.tableid=c2.tableid
INNER JOIN connector AS c3 ON c1.tableid=c3.tableid

WHERE
    (c1.memberid LIKE '+1%')
    AND (c2.memberID LIKE '56%')
    AND (c3.memberID = 6250)
    AND  c2.date BETWEEN '2013-12-04 0:00:00' and '2013-12-04 23:59:59'
    AND NOT EXISTS (SELECT 1 FROM connector c4 WHERE c1.tableid=c4.tableid AND c4.memberid = 6900)

答案 1 :(得分:0)

只需将其添加到代码的末尾:

... AND c1.tableid NOT IN (SELECT tableid FROM connector WHERE memberid = 6900);