需求:
两张表,线上课程表 course 表和线下表 classes 表。还有一张订单表。订单表中有一个字段platform 表示课程类型:0 表示线下, 1表示线上。需要关联查询相关订单信息。
问题: 如果分开查询,会导致排序的话会很麻烦,所以还是希望在sql 语句中处理。
解决:使用 sql 中的 case 来解决。
SELECT
a.id as orderId,
case a.platform when 0 then b.name when 1 then c.name end as name,
case a.platform when 0 then b.title when 1 then null end as title
FROM
order AS a
LEFT JOIN
classes AS b ON a.cid = b.id
LEFT JOIN
course AS c ON a.cid = c.id
order by a.created_at desc