mysql比较组内的2个表

时间:2014-02-26 21:41:59

标签: mysql

我有2张桌子

table A                      table B

pid date1                 pid date 2
a   10-12-2014            a   10-12-2014
a   11-13-2014            a   11-22-2011
                          a   8-9-2007
                          a   7-6-2006


b   9-10-2011             b  8-8-2011
                          b  9-5-2004
                          b  8-2-2005


c   8-8-2011              c 9-10-2001
                          c 8-8-2011

我想检查特定日期1是否在特定pid的日期2中有条目

for for pid a date1 10-12-2014退出日期2 10-12-2014

2 个答案:

答案 0 :(得分:2)

SELECT a.*, IF(b.pid IS NULL, false, true) entry_in_b FROM taba a
LEFT JOIN tabb b ON a.pid = b.pid AND a.date1 = b.date2

或类似的东西。

答案 1 :(得分:1)

此查询将返回Table A中与pid匹配date2Table B的所有行:

SELECT  A.pid,
        A.date1
  FROM  [Table A] A
    INNER JOIN [Table B] B ON B.pid = A.pid AND B.date2 = A.date1

如果要返回A中的所有行,并指示B中是否存在匹配的行:

SELECT  A.pid,
        A.date1,
        CASE
          WHEN B.date2 IS NULL THEN 'no match'
          ELSE 'match'
        END AS Match
  FROM  [Table A] A
    LEFT JOIN [Table B] B ON B.pid = A.pid AND B.date2 = A.date1