0

我正在尝试INNER JOIN从表中提取一行。查询返回行,直到我添加LIMIT 1代码行,然后它什么也不返回,对我来说没有任何意义。这是我的代码。

SELECT DISTINCT pd.pid, fv.flow_bmi, fv.flow_date
FROM patient_data pd
INNER JOIN ( ... )
INNER JOIN (
  SELECT pid, flow_bmi, flow_date
  FROM flow_vitals
  ORDER BY flow_date DESC
) fv ON fv.pid = pd.pid

#Results
-------------------------------
 pid  | flow_bmi  | flow_date
-------------------------------
 6073 | 31.90     | 2011-11-06
 6073 | 33.10     | 2011-11-05 <-- I don't want this row returned
 6072 | 32.10     | 2011-08-01

现在当我添加LIMIT 1

SELECT DISTINCT pd.pid, fv.flow_bmi, fv.flow_date
FROM patient_data pd
INNER JOIN ( ... )
INNER JOIN (
  SELECT pid, flow_bmi, flow_date
  FROM flow_vitals
  ORDER BY flow_date DESC
  LIMIT 1
) fv ON fv.pid = pd.pid

#Expected Outcome
-------------------------------
 pid  | flow_bmi  | flow_date
-------------------------------
 6073 | 31.90     | 2011-11-06
 6072 | 32.10     | 2011-08-01

#Actual Outcome
-------------------------------
 pid  | flow_bmi  | flow_date
-------------------------------
 No rows returned.

我不知道为什么LIMIT会破坏这一点,而我真正想要的是INNER JOIN根据最新日期仅返回一行。似乎有很多关于同一主题的问题,但他们最终使用了,MAX()或者LIMIT两者都对我不起作用。

4

1 回答 1

1

您实际上想要每组一行,而不是表中的一行flow_vitals。放在LIMIT 1那里只返回整个表格的第一行。

我假设您想要的行是具有最大值的flow_datepid。尝试:

SELECT DISTINCT pd.pid, fv.flow_bmi, flow_date
FROM patient_data pd
INNER JOIN ( ... )
INNER JOIN (
  SELECT pid, flow_bmi, flow_date
  FROM flow_vitals
) fv ON fv.pid = pd.pid
WHERE flow_date = (SELECT MAX(ffvv.flow_date) FROM flow_vitals ffvv WHERE ffvv.pid = fv.pid)

或者,作为连接:

SELECT DISTINCT pd.pid, fv.flow_bmi, flow_date
FROM patient_data pd
INNER JOIN ( ... )
INNER JOIN (
  SELECT pid, flow_bmi, flow_date
  FROM flow_vitals
) fv ON fv.pid = pd.pid
INNER JOIN (
  SELECT pid, MAX(flow_date) AS maxDate
  FROM flow_vitals
  GROUP BY pid
) fvMax ON fv.pid = fvMax.pid AND fv.flow_date = fvMax.maxDate

我也想知道DISTINCT这里是否真的有必要。

于 2012-11-05T18:36:55.350 回答