在MySQL中,当我在Subquery中使用Limit时,它什么都不返回?

时间:2012-11-05 18:30:55

标签: mysql row limit inner-join

我正在尝试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都不适用于我。

1 个答案:

答案 0 :(得分:1)

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

我假设您想要的行是flow_date的最大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
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