SQL数据表两个字段关联同一张数据表

时间:2022-04-18 15:13:58

数据表temp结构

-- Table "temp" DDL

CREATE TABLE `temp` (
  `page_id` bigint(20) DEFAULT NULL,
  `section_id` bigint(20) DEFAULT NULL,
  `visit_category_id` bigint(20) DEFAULT NULL,
  `cart_category_id` bigint(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
数据表category结构

-- Table "category" DDL

CREATE TABLE `category` (
  `category_id` bigint(20) DEFAULT NULL,
  `category_name` varchar(128) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
业务需求

关联temp表和category表,取出visit_category_id和cart_category_id对应的category_name

解决方案

select a.page_id,
a.section_id,
a.visit_category_id,
b.category_name,
a.cart_category_id,
c.category_name 
from temp a 
left outer join category b on (a.visit_category_id=b.category_id) 
left outer join category c on (a.cart_category_id=c.category_id);
查询结果

SQL数据表两个字段关联同一张数据表