如何在IFql条件中编写选择查询以代替mysql查询中的列名

时间:2018-02-15 09:53:59

标签: mysql

SELECT DISTINCT o.receipt,
if(SELECT status FROM list WHERE receipt = o.receipt GROUP BY receipt) as status 
FROM orderlist o 

编写上述查询的正确方法是什么如果条件并获得如下示例的结果。

相同的收据(orderId)有多个元组(行)和所有这个元组可能有不同的状态值。我想根据收据设置值(orderId)使用IF的第一个元组状态言。

IF(status = 'shipped', "Yes", "NO");

2 个答案:

答案 0 :(得分:1)

如果您的数据模型看起来像这样(即您有一种区分事件顺序的方法),则子查询中的限制可能会发生。

import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

DateTimeFormatter.ISO_INSTANT.format(OffsetDateTime.now().minusDays(1L))

结果

drop table if exists t,t1;

create table t(id int);
create table t1(id int, tid int, status varchar(10));

insert into t values (1),(2);
insert into t1 values (1,1,'a'),(2,1,'Shipped'),(3,1,'Returned'), (4,2,'shipped');

select t.id,
         if(
         (select status from t1 where t1.tid = t.id order by id limit 1)
         = 'Shipped','yes','no') shipped
from t;

但是货物通常不是最后的状态吗?

答案 1 :(得分:0)

试试这个。

SELECT DISTINCT o.receipt, CASE status when 'Shipped' then 'Yes' ELSE 'No' END as status 
FROM orderlist o join receipt r on o.receipt = r.receipt