sql开发学习(1)之group by,left join

SELECT c.id,
         c.name1,
         t.id,
         t.name3
FROM 
    (SELECT    id,
            name1
    FROM mytest.join_test1
    WHERE id>1
    GROUP BY  id, name1) c
LEFT JOIN 
    (SELECT    id,
            name3
    FROM mytest.join_test2
    WHERE id>1
    GROUP BY  id, name3) t
    ON t.id = c.id
        
     

表数据:   

mysql> select * from mytest.join_test1;
+------+---------+---------+
| id   | name1   | name2   |
+------+---------+---------+
|    1 | test1_1 | test1_1 |
|    3 | test1_3 | test1_3 |
|    4 | test1_4 | test1_4 |
|    5 | test1_5 | test1_5 |
|    2 | test1_2 | test1_2 |
+------+---------+---------+
5 rows in set (0.00 sec)

mysql> select * from mytest.join_test2;
+------+---------+---------+
| id   | name3   | name4   |
+------+---------+---------+
|    1 | test2_1 | test2_1 |
|    3 | test2_3 | test2_3 |
+------+---------+---------+
2 rows in set (0.00 sec)

查询结果:
+------+---------+------+---------+
| id   | name1   | id   | name3   |
+------+---------+------+---------+
|    2 | test1_2 | NULL | NULL    |
|    3 | test1_3 |    3 | test2_3 |
|    4 | test1_4 | NULL | NULL    |
|    5 | test1_5 | NULL | NULL    |
+------+---------+------+---------+
4 rows in set (0.00 sec)    

你可能感兴趣的:(sql,学习,数据库)