2017-09-04 42 views

回答

0

她的一些超級簡單的東西:

準備DB:

CREATE TABLE `table1` (
    `id` int(11) NOT NULL DEFAULT 0, 
    `value` text not null DEFAULT '', 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB; 

CREATE TABLE `table2` (
    `id` int(11) NOT NULL DEFAULT 0, 
    `value` text not null DEFAULT '', 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB; 

INSERT INTO table1 VALUES 
(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'); 

INSERT INTO table2 VALUES 
(3, 'three'), (4, 'four'), (5, 'five'), (6, 'six'), (7, 'seven'); 

執行查詢:

SELECT t1.*, t2.* FROM table1 t1 JOIN table2 t2 on t1.id = t2.id; 
SELECT t1.*, t2.* FROM table1 t1 INNER JOIN table2 t2 on t1.id = t2.id; 
+----+-------+----+-------+ 
| id | value | id | value | 
+----+-------+----+-------+ 
| 3 | three | 3 | three | 
| 4 | four | 4 | four | 
| 5 | five | 5 | five | 
+----+-------+----+-------+ 
SELECT t1.*, t2.* FROM table1 t1 LEFT JOIN table2 t2 on t1.id = t2.id; 
SELECT t1.*, t2.* FROM table1 t1 LEFT OUTER JOIN table2 t2 on t1.id = t2.id; 
+----+-------+------+-------+ 
| id | value | id | value | 
+----+-------+------+-------+ 
| 1 | one | NULL | NULL | 
| 2 | two | NULL | NULL | 
| 3 | three | 3 | three | 
| 4 | four | 4 | four | 
| 5 | five | 5 | five | 
+----+-------+------+-------+ 
0

比方說,你有2個表:

ID Name 
1 Smith 
2 Novak 
3 Tarantino 

和第二表

ID Cash 
2 300 
3 490 
4 500 

INNER JOIN將加入有匹配這兩個表中,即在結果表中只有ID 2和3將被包括在內,因爲它們具有匹配的記錄。 結果會是什麼樣子:

ID Name  Cash 
2 Novak  300 
3 Tarantino 490 

OUTER JOIN,另一方面,將匹配一切,而不管它們是否具有匹配與否。如果記錄不匹配,那麼對應於某一行的值將是NULL,即Smith將在Cash列中具有NULL列,並且在Cash列中將對應於500的記錄列將在Name列中具有NULL列。 結果會是什麼樣子:

ID Name  Cash 
1 Smith  NULL 
2 Novak  300 
3 Tarantino 490 
4 NULL  500 
+0

非常感謝您 –

+0

請接受的答案,如果它符合你的要求,所以它不會需要從用戶和管理員的任何更多的關注。 –

相關問題