如何在内连接上进行连接?

时间:2011-08-31 23:29:43

标签: php mysql join inner-join

我有这个数据库:

table

id  fname       dphone      count_pic   dup_id  

6055903 Karla       5126xxx798  1       57  
6173767 Aaliyah     4082xxx534  4       39  
5611411 Aaliyah     4082xxx534  15      39  
5611211 Aaliyah     4082xxx534  18      39  
4234798 Abby        3057xxx974  31      16  
6166691 Walter      6178xxx280  1       74  
3375576 Walter      6178xxx280  17      74

我发现了如何对它进行内连接:

SELECT *
  FROM table t1
INNER JOIN (SELECT MIN(count_pic) AS minpic,
               MAX(count_pic) AS maxpic,
               dup_id
          FROM table
      GROUP BY dup_id) t2 ON t1.dup_id = t2.dup_id
                         AND (t1.count_pic = minpic
                           OR t1.count_pic = maxpic)

但如果我想将此表与基于id的另一个表连接并返回一些值,例如第二个表中的date,,该怎么办:

table2

    id  date

6055903 111111111
6173767 111111111
5611411 111111111

有关于此的任何想法吗?

编辑:

内部联接很好,我需要在该查询之上添加table2

1 个答案:

答案 0 :(得分:0)

最后添加另一个JOIN

SELECT *
  FROM table t1
INNER JOIN (SELECT MIN(count_pic) AS minpic,
               MAX(count_pic) AS maxpic,
               dup_id
          FROM table
      GROUP BY dup_id) t2 ON t1.dup_id = t2.dup_id
                         AND (t1.count_pic = minpic
                           OR t1.count_pic = maxpic)

INNER JOIN table2 ON t1.id = table2.id -- add this