我有两张桌子:
connections
id | publisherId | authorId
和
books
id | connectionId | title
我想合并这些表来只得到一个表:
books
id| publisherId | authorId | title
我怎样才能只用一个 SQL 查询来做到这一点?
CREATE TABLE newtable
SELECT b.id, c.publisherId, c.authorID, b.title
FROM books b
INNER JOIN connections c
on c.id = b.connectionId
未经测试,但这应该可以。我假设您需要 books 表中的 ID,否则您需要 c.id 而不是 b.id。
然后您可以删除旧表并将其重命名为您想要的任何名称。
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 ...
每个选定列的名称。