子查询(理解性入门)

子查询

  • 子查询:一条select语句结果作为另一条select语法一部分(理解便容易做题);
  • select … from … where …(基于这个基础语法做出的改变)

– # 子查询, 查询“化妆品”分类上架商品详情
– 1) 查询分类,条件 化妆品

select cid from category where cname = ‘化妆品’

– 2) 查询c003商品详情

select * from products where category_id = ‘c003’ and flag = ‘1’;

– 3) 组合

select * from products where category_id = ( select cid from
category where cname = ‘化妆品’ ) and flag = ‘1’;

上面语句是用于理解,下面我会提供相应的建表语句,

create database en003;
use en003;

CREATE TABLE category (
  cid VARCHAR(32) PRIMARY KEY ,
  cname VARCHAR(50)
);
CREATE TABLE products(
  pid VARCHAR(32) PRIMARY KEY ,
  pname VARCHAR(50),
  price INT,
  flag VARCHAR(2),				#是否上架标记为:1表示上架、0表示下架
  category_id VARCHAR(32),
  CONSTRAINT products_fk FOREIGN KEY (category_id) REFERENCES category (cid)
);

#分类
INSERT INTO category(cid,cname) VALUES('c001','家电');
INSERT INTO category(cid,cname) VALUES('c002','服饰');
INSERT INTO category(cid,cname) VALUES('c003','化妆品');
#商品
INSERT INTO products(pid, pname,price,flag,category_id) VALUES('p001','联想',5000,'1','c001');
INSERT INTO products(pid, pname,price,flag,category_id) VALUES('p002','海尔',3000,'1','c001');
INSERT INTO products(pid, pname,price,flag,category_id) VALUES('p003','雷神',5000,'1','c001');

INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p004','JACK JONES',800,'1','c002');
INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p005','真维斯',200,'1','c002');
INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p006','花花公子',440,'1','c002');
INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p007','劲霸',2000,'1','c002');

INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p008','香奈儿',800,'1','c003');
INSERT INTO products (pid, pname,price,flag,category_id) VALUES('p009','相宜本草',200,'1','c003');

大家可以试着做一下,如此才会更加理解。

你可能感兴趣的:(基础语法,mysql,数据库,java)