我有以下设置:
CREATE TABLE A(id INT);
CREATE TABLE B(id INT);
CREATE TABLE C(aid INT, bid INT);
我想做以下事情:
INSERT INTO C SELECT A.id as aid, (SELECT B.id FROM B WHERE A.id=B.id)
AS bid FROM A WHERE bid is not NULL;
但是,它会出现列出价不存在的错误。那么有没有办法在横向连接中引用输出行或仅在bid
不为空的情况下进行插入?
我想保留横向连接。
答案 0 :(得分:2)
你不能像这样引用别名,你需要包装select:
INSERT INTO C
SELECT *
FROM (
SELECT A.id as aid,
(SELECT B.id FROM B WHERE A.id=B.id) AS bid
FROM A
) t
WHERE bid is not NULL;