I’m trying to INNER JOIN a single row from a table. The query returns rows until I add the LIMIT 1 line of code and then it returns nothing and it doesn’t make any sense to me. Here is my code.
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
And now when I add 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.
I don’t know why LIMIT breaks this, and what I really want is an INNER JOIN that returns only one row based on the latest date. It seems like there are a ton of questions on this same topic but they end up using MAX() or LIMIT which both have not worked for me.
You actually want one row per group, not one row total from the
flow_vitalstable. Putting aLIMIT 1there returns just the top row from the entire table.I assume the row you want is the one with the maximum
flow_datefor thatpid. Try:Or, as a join:
I also wonder if
DISTINCTis really necessary here.