mysql:如何从两个表中选择

时间:2019-03-20 11:10:09

标签: mysql sql mysqli

我有两个具有相同键ID的表,但是其中一个表比另一个表具有更多的记录,因此内部联接不起作用。 我的查询结果仅显示两个表的通用记录:

   t1:
   ---------------------
   id, data
   ----------------------
   1,aaa
   2,bbb
   4,ccc


   t2: 
   -------------------
   id
   -------------------
   1
   2
   3
   4
   5

   join result :
   -------------------
   1,aaa
   2,bbb
   3,null
   4,ccc
   5,null

此查询无法完成工作:

$query=" SELECT t2.id, t1.data FROM table1 t1
         INNER JOIN table2 t2
         ON t1.id = t2.id
         ORDER BY t2.id     " ;

3 个答案:

答案 0 :(得分:4)

请尝试这个。

$query=" SELECT t2.id, t1.data FROM table1 t1
         RIGHT JOIN table2 t2
         ON t1.id = t2.id
         ORDER BY t2.id" ; 

答案 1 :(得分:2)

mysql> create table t1(id int,data varchar(20));
Query OK, 0 rows affected (0.36 sec)

mysql> insert into t1 values(1,'aaa'),(2,'bbb'),(4,'ccc');
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> create table t2(id int);
Query OK, 0 rows affected (0.36 sec)

mysql> insert into t2 values(1),(2),(3),(4),(5);
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select t2.id,t1.data from t2 left join t1 on (t2.id = t1.id);
+------+------+
| id   | data |
+------+------+
|    1 | aaa  |
|    2 | bbb  |
|    4 | ccc  |
|    3 | NULL |
|    5 | NULL |
+------+------+
5 rows in set (0.00 sec)

mysql> 

答案 2 :(得分:1)

好吧,您提供的查询可以按INNER JOIN操作的预期运行。

    SELECT t2.id, t1.data 
      FROM table1 t1
INNER JOIN table2 t2
        ON t1.id = t2.id
  ORDER BY t2.id

会产生:

| id | data |
| 1  | aaa  |
| 2  | bbb  |
| 4  | ccc  |

如果您想查看第二个表中的所有值,则需要在LEFT JOIN表上进行table2操作。

    SELECT t2.id, t1.data 
      FROM table2 t2
 LEFT JOIN table1 t1
        ON t1.id = t2.id

会产生:

| id | data   |
| 1  | aaa    |
| 2  | bbb    |
| 3  | (null) |
| 4  | ccc    |
| 5  | (null) |