1

I have two mysql tables that have the following structure:

Table 1:

---ID---------NAME-------
---1----- page name 1 ---
---2----- page name 2 ---
---3----- page name 3 ---

Table 2:

----ID---PAGE ID---------NAME------
-----1-----1-------- page name 1 ---
-----2-----2-------- page name 2 ---
-----3-----3-------- page name 3 ---
-----4-----1-------- page name 1 ---
-----5-----2-------- page name 2 ---
-----6-----3-------- page name 3 ---
-----7-----1-------- page name 1 ---
-----8-----2-------- page name 2 ---
-----9-----3-------- page name 3 ---

As you can see in table 2 each page is mentioned several times.

I want to join Table 1 on Table 2 only with the newest records in Table 2, in this case the newest three records only! ("newest" means records with higher IDs) Is that possible using mysql?

6
  • 2
    What defines "newest record"? The ones with the highest IDs? A date/time field you've not listed? Commented Mar 15, 2011 at 14:30
  • Define "newest". I cannot see any timestamp in Table2 (that is not really your table name, is it?) Commented Mar 15, 2011 at 14:30
  • And also which field in Table2 is the foreign key that relates it to Table1? Commented Mar 15, 2011 at 14:31
  • "Newest" means highest IDs... Commented Mar 15, 2011 at 14:32
  • What's the difference between Table1.Name and Table2.Name? Is that data just duplicated? Commented Mar 15, 2011 at 14:36

2 Answers 2

1

Table2

----ID---PAGE ID----
-----1-----1-------- 
-----2-----2-------- 
-----3-----3-------- 
-----4-----1-------- 
-----5-----2-------- 
-----6-----3-------- 
-----7-----1-------- 
-----8-----2-------- 
-----9-----3-------- 

and

SELECT Table1.ID, PAGE_ID, NAME
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.PAGE_ID
WHERE ... put your condition for latest if other when highest ID
ORDER BY Table1.ID DESC
LIMIT 3
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT Table1.ID, PAGE_ID, NAME 
FROM Table1 
LEFT JOIN Table2 ON Table1.ID = Table2.PAGE_ID 
WHERE Table2.ID = MAX(Table2.ID) 
GROUP BY Table1.ID 
LIMIT 3

should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.