Reputation: 2741
It's been a while since I've used MySQL. I can't remember what the best way and exact technique is called for getting different types of data from multiple sql tables.
I'm building a shell page to load data from legacy websites and I'm simply trying to load the most recent three blog postings where the title is in one table, a username is in another and the posting's url is in another.
I do not want to only get three postings where they are from the same user. Think I'm getting confused there.
Essentially I'd want to be able to print all the records out like this
1, 17, 2, "First Post", "bob", "dole", "/first-post"
2, 18, 2, "Second Post", "bob", "dole", "/second-post"
3, 19, 1, "Third Post", "ron", "unix", "/third-post"
content.contentid = urls.assocId (for url) content.author = users.userId (for username)
create table content (
id int,
contentid int,
author int,
title varchar(16)
);
create table users (
id int,
userId int,
firstName varchar(16),
lastName varchar(16)
);
create table urls (
id int,
assocId int,
url varchar(16)
);
insert into content values
(1, 17, 2, "First Post"),
(2, 18, 2, "Second Post"),
(3, 19, 1, "Third Post");
insert into users values
(1,1,"bob", "dole"),
(2,2,"ron", "unix");
insert into urls values
(1, 17, "/first-post"),
(2, 18, "/second-post"),
(3, 19, "/third-post");
http://sqlfiddle.com/#!9/e99cf
Thanks
Upvotes: 0
Views: 40
Reputation: 780949
Just a simple INNER JOIN
between the 3 tables.
SELECT c.id, c.contentid, u.userId, u.firstName, u.lastName, urls.url
FROM content AS c
JOIN users AS u ON c.author = u.id
JOIN urls ON c.contentid = urls.assocId
ORDER BY c.id DESC
LIMIT 3
If you have a date
field in the content
table, you can use that for the ORDER BY
column to get the most recent in time. I've used the id
field instead in my example.
Upvotes: 2