Answer the question
In order to leave comments, you need to log in
What is the best way to join one single line out of many?
Good afternoon, ladies and gentlemen.
There is a request. I won't give the whole story, just the important points.
SELECT * FROM tbl1 LEFT JOIN tbl2 USING(field1) WHERE tbl2.field2 > 0;
SELECT * FROM tbl1
LEFT JOIN tbl2 ON tbl2.pk = (SELECT pk FROM tbl2 WHERE tbl2.field1 = tbl1.field1 ORDER BY ... LIMIT 1)
WHERE tbl2.field2 > 0
Answer the question
In order to leave comments, you need to log in
Of course, it squanders, you use a correlating subquery (in a query nested in tbl2, a selection from tbl1) ....
SELECT * FROM tbl1
LEFT JOIN tbl2
ON tbl2.pk = (SELECT pk FROM tbl2 WHERE tbl2.field1 = tbl1.field1 ORDER BY ... LIMIT 1)
WHERE tbl2.field2 > 0
SELECT * FROM tbl1
LEFT JOIN tbl2
ON tbl2.field1 = tbl1.field1
WHERE tbl2.field2 > 0
ORDER BY tbl2.pk DESK LIMIT 1
Answered a similar question here.
The solution was:
SELECT *
FROM main m
LEFT JOIN extra e1 ON m.id = e1.main_id
LEFT JOIN extra e2 ON e1.main_id = e2.main_id AND e2.date > e1.date
WHERE e2.date IS NULL AND e1.status = 1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question