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;

解释

  1. 使用 select * from fruit, price where fruit.price_id=price.id 进行查询,会返回所有列,包括 id 列。

  2. 使用 select fruit.name, price.price from fruit, price where fruit.price_id=price.id 只返回 fruit.nameprice.price 两列,满足需求。

注意

  • 使用 JOIN 操作可以使代码更加简洁易懂,但需要根据具体情况选择合适的 JOIN 类型。
  • 当使用 JOIN 操作时,可以使用 ON 子句来指定连接条件。
  • 可以使用 WHERE 子句来过滤数据。
  • 可以使用 ORDER BY 子句来排序数据。
MySQL 多表查询:水果名称和价格

原文地址: https://www.cveoy.top/t/topic/or6l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录