MySQL 多表查询:水果名称和价格
MySQL 多表查询:水果名称和价格
数据库结构
create table price(
id int primary key auto_increment,
price double
);
-- 水果表
create table fruit(
id int primary key auto_increment,
name varchar(20) not null,
price_id int,
foreign key(price_id) references price(id)
);
insert into price values(1,2.30);
insert into price values(2,3.50);
insert into price values(4,null);
insert into fruit values(1,'苹果',1);
insert into fruit values(2,'橘子',2);
insert into fruit values(3,'香蕉',null);
查询需求
查询两张表中关于水果的信息,要显示水果名称和水果价格。
查询语句
select * from fruit,price where fruit.price_id=price.id
-- 去除笛卡尔积中非法数据的条件(一般都是外键=主键)
fruit.price_id=price.id
-- 查询结果只需要显示水果名称和价格,不需要显示id
select fruit.name, price.price from fruit, price where fruit.price_id=price.id;
解释
-
使用
select * from fruit, price where fruit.price_id=price.id进行查询,会返回所有列,包括id列。 -
使用
select fruit.name, price.price from fruit, price where fruit.price_id=price.id只返回fruit.name和price.price两列,满足需求。
注意
- 使用
JOIN操作可以使代码更加简洁易懂,但需要根据具体情况选择合适的 JOIN 类型。 - 当使用
JOIN操作时,可以使用ON子句来指定连接条件。 - 可以使用
WHERE子句来过滤数据。 - 可以使用
ORDER BY子句来排序数据。
原文地址: https://www.cveoy.top/t/topic/or6l 著作权归作者所有。请勿转载和采集!