0
我有以下SQL代碼來創建和德比填充了幾桌:德比使用INSERT SELECT SQL
CREATE TABLE GROUPS (
GRP_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY,
GRP_NAME VARCHAR(256) NOT NULL,
DISPLAY_NAME VARCHAR(256));
CREATE TABLE USERS (
USR_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) PRIMARY KEY,
USR_NAME VARCHAR(256) NOT NULL,
PASSWORD VARCHAR(512) NOT NULL,
DISPLAY_NAME VARCHAR(256));
CREATE TABLE USR_GRP_MEMBERSHIP (
USR_ID INTEGER NOT NULL REFERENCES USERS ON DELETE CASCADE,
GRP_ID INTEGER NOT NULL REFERENCES GROUPS ON DELETE CASCADE,
CONSTRAINT USR_ID_GRP_ID UNIQUE (USR_ID, GRP_ID));
INSERT INTO GROUPS(GRP_NAME, DISPLAY_NAME) VALUES('Users', 'Users');
INSERT INTO GROUPS(GRP_NAME, DISPLAY_NAME) VALUES('AdminUsers', 'Administrators');
INSERT INTO USERS(USR_NAME, PASSWORD, DISPLAY_NAME) VALUES('user', 'userpwd', 'User');
INSERT INTO USERS(USR_NAME, PASSWORD, DISPLAY_NAME) VALUES('admin', 'adminpawd', 'Administrator');
#The following code populates the USR_GRP_MEMBERSHIP table using the IDs of users
#& groups inserted in the previous set of insert statements
INSERT INTO USR_GRP_MEMBERSHIP VALUES((SELECT USR_ID FROM USERS WHERE USR_NAME = 'user'), (SELECT GRP_ID FROM GROUPS WHERE GRP_NAME = 'Users'));
INSERT INTO USR_GRP_MEMBERSHIP VALUES((SELECT USR_ID FROM USERS WHERE USR_NAME = 'admin'), (SELECT GRP_ID FROM GROUPS WHERE GRP_NAME = 'Users'));
INSERT INTO USR_GRP_MEMBERSHIP VALUES((SELECT USR_ID FROM USERS WHERE USR_NAME = 'admin'), (SELECT GRP_ID FROM GROUPS WHERE GRP_NAME = 'AdminUsers'));
我的問題是:在過去的3個INSERT
語句有SELECT
聲明中他們重複。如何將這些SELECT語句的輸出存儲在一個變量中並在這3個語句中使用它們?
是的,這是可以做到的,但這將是在JAVA代碼中,我正在尋找一種方法來在SQL代碼本身做到這一點! :) – Curious 2014-12-02 17:25:40