插入左连接SQL

时间:2014-02-24 10:34:09

标签: mysql sql

我需要以下SQL

的帮助

我有两个表titlespostcode_db我想要LEFT JOIN并插入第三个表

SELECT titles.id, titles.title, titles.address, 
postcode_db.postcode, postcode_db.suburb
FROM titles
LEFT JOIN postcode_db ON titles.address = postcode_db.suburb;

以上作品。我想插入titles_postcode

titles.id AS titles_postcode.title_id

titles.title AS titles_postcode.title

postcode_db.postcode

INSERT INTO titles_postcode 
(titles.id AS titles_postcode.title_id, 
titles.title AS titles_postcode.title, 
postcode_db.postcode AS titles_postcode.postcode)
SELECT titles.id, titles.title, titles.address, 
postcode_db.postcode, postcode_db.suburb
FROM titles
LEFT JOIN postcode_db ON titles.address = postcode_db.suburb;

返回error right syntax to use near 'AS titles_postcode.title_id, titles.title AS titles_postcode.title, postcode_db.' at line 1

3 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO titles_postcode (title_id, title, postcode)
SELECT titles.id, titles.title, postcode_db.postcode
FROM titles
LEFT JOIN postcode_db ON titles.address = postcode_db.suburb;

答案 1 :(得分:1)

您不应在插入查询中使用别名,并且您的值与列数不匹配,我认为您只需要插入这3列

INSERT INTO titles_postcode  (title_id, title, postcode)
SELECT titles.id, titles.title, postcode_db.postcode
FROM titles
LEFT JOIN postcode_db 
ON titles.address = postcode_db.suburb;

答案 2 :(得分:1)

INSERT INTO titles_postcode(title_id,title,postcode) 
SELECT titles.id, titles.title, titles.address, 
postcode_db.postcode
FROM titles
LEFT JOIN postcode_db ON titles.address = postcode_db.suburb;