我有什么:
表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来完成此任务。
答案 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;
这会给你:
| 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;
答案 1 :(得分:3)
答案 2 :(得分:0)
应该这样做,
SELECT a.id, name, age, occupation, address
FROM table1 a, table2 b
WHERE a.id = b.id;