如何将“价值”带出;“存在”;查询(MYSQL)?

如何将“价值”带出;“存在”;查询(MYSQL)?,mysql,sql,Mysql,Sql,好的,我有两张桌子: OrderTable (orderID is unique) orderID - Date ..... 1 - 11/12 .... 2 - 12/12 .... .... OrderStage (each orderID has many stages) orderID - Stage 1 - 1 1 - 3 2 - 2 2 - 4 .... 上面的查询可以工作,但我不知道如何将Max stage从

好的,我有两张桌子:

OrderTable (orderID is unique) orderID - Date ..... 1 - 11/12 .... 2 - 12/12 .... .... OrderStage (each orderID has many stages) orderID - Stage 1 - 1 1 - 3 2 - 2 2 - 4 .... 上面的查询可以工作,但我不知道如何将Max stage从
OrderStage
表中带出来,这样结果将是:

orderID - Date ..... - MaxStage 1 - 11/12 .... - 3 但是MYSQL显示了错误

那么如何解决这个问题呢


注意:我不能使用JOIN,因为我在一个非常复杂的现有sql上构建此查询,如果我更改为JOIN,则可能会破坏代码。

如果要使用值,则需要使用
JOIN

select ot.orderID,..., omax.maxStage
From orderTable ot inner join
     (select orderID, MAX(stage) as maxStage
      from OrderStage 
      group by orderID
      Having MAX(stage)=3
     ) omax
     on ot.orderId = omax.orderId;

内部连接
进行过滤,由于
按医嘱ID分组
,您不必担心结果集中的行被无意中复制。

我们可以不使用连接吗?我记得我在学校学过,他们可以在不使用连接的情况下从存在中提取值,但忘记了how@Tum . . . 然后你误学了SQL。这是不可能的。
select
子句中的变量来自
from
子句。
select orderID,..., st.maxStage From orderTable where  
exists (select orderID, MAX(stage) maxStage from OrderStage 
group by orderID Having MAX(stage)=3 ) st
select ot.orderID,..., omax.maxStage
From orderTable ot inner join
     (select orderID, MAX(stage) as maxStage
      from OrderStage 
      group by orderID
      Having MAX(stage)=3
     ) omax
     on ot.orderId = omax.orderId;