Two questions.
One: How would I be able to join two tables together, which are not the original FROM 'x' table?
Example: Grabbing all the reports and that users level name.
Report
id | user_id
1 1
User
id | level_id
1 1
Level
id | level_name
1 Admin
SELECT report.id,
report.user_id,
level.name
FROM report
INNER JOIN user
ON report.user_id=user.id
INNER JOIN level
ON user.level_id=level.id
Doesn't seem to work.
Two: How to join tables not from a 1-1 but a 1-many?
Say I wanted t开发者_JS百科o:
SELECT * FROM user JOIN report ON user.id=report.user_id WHERE user.id='4'
But only join with the most recent report ordered by date desc?
I know it seems like I am asking you to do my work for me, but I just need to know what to use to accomplish this, not necessarily you coding it. Thanks.
UPDATE:
First question: Fixed, thanks Second question:
I'll show you my query to make better sense, I didn't explain it well. I meant a many-many relationship where I grab a list of users and their latest report!
SELECT
user.id
FROM
user
<< INNER JOINS ON OTHER TABLES >>
INNER JOIN
(
SELECT
report.id
FROM
report
WHERE user.id=report.user_id
ORDER BY
date
DESC
LIMIT 1
)
For your second question:
MySQL-style:
SELECT *
FROM user
INNER JOIN report re
ON re.id = (SELECT id
FROM report
WHERE user_id=user.id
ORDER BY report.date DESC
LIMIT 1)
WHERE user.id='4'
One: Looks good to me, but shouldn't that be level.level_name in the SELECT clause?
Two: If you just want the most recent report it would be something like...
SELECT TOP 1 * FROM user JOIN report ON user.id=report.user_id WHERE user.id='4' order by report.date desc
精彩评论