views:

102

answers:

4

I'm tired and I can't wrap my head around this. I have two tables:

table menu
@id = id, @nr = id of parent
|======|======|  
|  id  |  nr  |
|======|======|
|  10  |   9  |
|  11  |  10  |
|  12  |  10  |
|  13  |  10  |
|======|======|

table content
@id = id, @mf = menu - first in tree, @mi = menu item linked to content
|======|======|======|
|  id  |  mf  |  mi  |
|======|======|======|
|  85  |   9  |  11  |
|  89  |   9  |  12  |
|  95  |   9  |  13  |
|======|======|======|

Now, I need to select all rows from content, where (mi = menu.id), but i need to select menu.id from menu first by selecting * from menu where nr = 10 (or any number, which I put to my sql with PHP)

I really can't wrap my head around all those UNIONS, LEFT JOINS, HAVING and stuff...

Thank you

Edit: Thank you ALL, shame I can pick just one good :)

+1  A: 

Is this what you're asking for? The following will return all rows in content where mi is in menu.id and nr=10.

select *
from content
where mi in (select id from menu where nr=10)
Aaron
This will work, but a JOIN is much more efficient.
Winston Smith
@Winston, he was first, tried to help and needs reputation more than you do :D Although, thank you for your solution also, got upvoted - and we talk about site with +/- 500 hits per day with the inner select with max 35 items, so efficiency is not thing here :]
Adam Kiss
@Adam - While it might not be important **this** time, but perhaps it's helpful to understand the differences in both solutions so that you have a wider range of tools at your disposal *next* time.
Winston Smith
A good optimizer should (in theory) be able to turn a subquery like this into a join, but I don't think MySQL can. You can check with EXPLAIN.
ephemient
@Winston - that's why **this** time i picked Aaron's answer as good... and when I'll understand the thing more, I'll appreciate your solution :)
Adam Kiss
A: 

SELECT * FROM content WHERE mi IN(SELECT id FROM menu WHERE nr = 10)

Tufo
A: 

untested

SELECT content.* FROM content, menu WHERE menu.nr = 10 AND content.mi = menu.id

or

SELECT c.*, menu.nr FROM menu LEFT JOIN content AS c ON menu.id = c.mi WHERE menu.nr = 10

davidosomething
+6  A: 
SELECT C.* FROM content C
INNER JOIN menu ON C.mi = menu.id AND menu.nr = 10;

UPDATE:

In response to your comment, you might find the W3 Schools section on SQL JOINS a helpful resource to get started with.

Winston Smith
Thank you, although I picked simpler looking answer, I will look into your response, try to understand it and learn from it :]
Adam Kiss