更改数据库结构:需要SQL查询

时间:2012-05-10 02:11:12

标签: mysql sql database

我有两张桌子:

connections
id | publisherId | authorId

books
id | connectionId | title

我想合并这些表只能得到一个表:

books
id| publisherId | authorId | title

如何只使用一个SQL查询?

2 个答案:

答案 0 :(得分:3)

CREATE TABLE newtable
SELECT b.id, c.publisherId, c.authorID, b.title
FROM books b
INNER JOIN connections c
on c.id = b.connectionId

未经测试,但应该这样做。我假设你想要书籍表中的ID,否则你需要c.id而不是b.id。

然后你可以删除旧表并将其重命名为你想要的任何内容。

答案 1 :(得分:0)

CREATE TABLE connections_books 
SELECT books.id as id, 
       connections.publisherId as publisherId, 
       connections.authorId as authorId, 
       books.title as title 
FROM books join connections on books.connectionId = connections.id;

首先仅使用select部分测试查询:

SELECT books.id as id, 
       connections.publisherId as publisherId, 
       connections.authorId as authorId, 
       books.title as title 
FROM books join connections on books.connectionId = connections.id;

一旦这给你你想要的东西,继续创建表。

确保新表中的列名称正确非常重要。使用select语句测试确保您的列名称符合您的要求。如果要更改列名称,请更改所选每列的as ...名称。