在MySQL中连接两个表

时间:2013-02-03 11:28:03

标签: mysql sql

我有什么:

表1

╔════╦═══════╦═════╗
║ ID ║ NAME  ║ AGE ║
╠════╬═══════╬═════╣
║  0 ║ John  ║  15 ║
║  1 ║ Chris ║  20 ║
╚════╩═══════╩═════╝

表2

╔════╦════════════╦═════════════╗
║ ID ║ OCCUPATION ║   ADDRESS   ║
╠════╬════════════╬═════════════╣
║  0 ║ Bus Driver ║ None        ║
║  1 ║ Lawyer     ║ some adress ║
╚════╩════════════╩═════════════╝

期望的输出

表3

╔════╦═══════╦═════╦════════════╦═════════════╗
║ ID ║ NAME  ║ AGE ║ OCCUPATION ║   ADDRESS   ║
╠════╬═══════╬═════╬════════════╬═════════════╣
║  0 ║ John  ║  15 ║ Bus Driver ║ None        ║
║  1 ║ Chris ║  20 ║ Lawyer     ║ some adress ║
╚════╩═══════╩═════╩════════════╩═════════════╝

虽然我可以使用PHP mysql_query("SELECT .. "); mysql_query("INSERT .."); -ish方式完成此任务,但我想使用纯SQL来完成此任务。

3 个答案:

答案 0 :(得分:5)

JOIN两个表:

SELECT
  t1.ID,
  t1.Name,
  t1.Age,
  t2.Occupation,
  t2.Address
FROM table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID;

SQL Fiddle Demo

这会给你:

| ID |  NAME | AGE | OCCUPATION |     ADDRESS |
-----------------------------------------------
|  0 |  John |  15 | Bus Driver |        None |
|  1 | Chris |  20 |     Lawyer | some adress |

如果您想直接从此选择中创建新表table3,请执行以下操作:

CREATE Table Table3
AS 
SELECT
  t1.Name,
  t1.Age,
  t2.Occupation,
  t2.Address
FROM table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID;

Like this

答案 1 :(得分:3)

试试这个

 SELECT t1.* , t2.* 
 FROM table1 t1, table2 t2
 WHERE t1.id = t2.id

SQL FIDDLE DEMO

答案 2 :(得分:0)

应该这样做,

SELECT a.id, name, age, occupation, address
FROM table1 a, table2 b
WHERE a.id = b.id;