/    Sign up×
Community /Pin to ProfileBookmark

JOIN SELECT Single Row

I have a table. Which has an index ID on it and a bunch of other data. I then have a second table with it’s own unique ID but also the parentID from table 1. In addition to this on table 2 I have a varchar and date column.

What I want to do it select all records from table 1. (easy) Then 1 row from table 2 for each corresponding parentID. The row I want is the the row with the latest date so sorting by date column and limiting to 1 record I assume.

How can I join the two tables, order and limit the second table only?

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJul 27.2021 — Maybe...
[code=sql]
select t1.*, t2.*
from table_1 as t1
inner join (
select * from table_2
where parentID = t1.ID
order by date_col desc limit 1
) as t2
[/code]

Change the inner join to left join if you want all rows from the first table even if they don't have a match in the 2nd table.

Untested, but I'm about 85% confident. :)
Copy linkTweet thisAlerts:
@kiwisauthorJul 27.2021 — @NogDog#1634802

can you do this is parentID is part of the first select, such as t1.ID = t2.ID
Copy linkTweet thisAlerts:
@NogDogJul 28.2021 — @kiwis80#1634804

My first approach failed, so I tried this. See if you think it solves what you're looking for...

http://sqlfiddle.com/#!9/c648ec/1

For posterity's sake, the SQL I used there:
[code=sql]
select m.*, c.*
from main m
inner join child c on c.parent_id = m.id
where c.id = (
select id from child
where parent_id = m.id
order by date desc limit 1
)
[/code]

Feels ugly, but seems to work.
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.23,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...