Oracle基本SQL操作-SQL语句
-- 创建用户表
CREATE TABLE users (
id NUMBER PRIMARY KEY,
username VARCHAR2(50) NOT NULL,
password VARCHAR2(50) NOT NULL,
email VARCHAR2(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 插入用户数据
INSERT INTO users (id, username, password, email) VALUES (1, 'user1', 'pass1', 'user1@example.com');
INSERT INTO users (id, username, password, email) VALUES (2, 'user2', 'pass2', 'user2@example.com');
INSERT INTO users (id, username, password, email) VALUES (3, 'user3', 'pass3', 'user3@example.com');
-- 查询用户数据
SELECT * FROM users;
-- 更新用户数据
UPDATE users SET email = 'updated@example.com' WHERE id = 1;
-- 删除用户数据
DELETE FROM users WHERE id = 2;
-- 创建角色表
CREATE TABLE roles (
id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 插入角色数据
INSERT INTO roles (id, name) VALUES (1, 'Admin');
INSERT INTO roles (id, name) VALUES (2, 'User');
-- 创建用户角色关联表
CREATE TABLE user_roles (
user_id NUMBER NOT NULL,
role_id NUMBER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (role_id) REFERENCES roles (id),
PRIMARY KEY (user_id, role_id)
);
-- 插入用户角色关联数据
INSERT INTO user_roles (user_id, role_id) VALUES (1, 1);
INSERT INTO user_roles (user_id, role_id) VALUES (3, 2);
-- 查询用户角色关联数据
SELECT u.username, u.email, r.name
FROM users u
JOIN user_roles ur ON u.id = ur.user_id
JOIN roles r ON ur.role_id = r.id
WHERE u.id = 1;
这个示例代码展示了如何在Oracle数据库中创建表、插入数据、更新数据、删除数据、以及如何通过JOIN查询关联表中的数据。这些操作是数据库管理和应用开发中的基本技能。
评论已关闭