tags:

views:

38

answers:

3

2 tables:

name  
id | title

and

content  
name | title

One name has several contents. name.id ~ content.name

I need to get 3 names with all theirs content.

SELECT name.title, content.title
FROM name LEFT JOIN content ON name.id = content.name
LIMIT 3

result in 3 contents, not names

Is it possible to do this with one query?

+1  A: 

Try this:

SELECT name.title, content.title, content.name
FROM name LEFT JOIN content ON name.id = content.name
LIMIT 0, 3

Also, you need to use an alias because you are selecting two title fields:

SELECT (name.title) as name_title, content.title, content.name
FROM name LEFT JOIN content ON name.id = content.name
LIMIT 0, 3

Update:

I think you need only the name field as far as i could figure out from your comment, try this:

SELECT content.name
FROM name LEFT JOIN content ON name.id = content.name
LIMIT 0, 3
Sarfraz
+1 for mentioning the alias...this definitely clears it up
espais
problem is that i dont know how many results should i get. I need 3 names, but they can contain from 3 up to ∞ contents
Qiao
@Qiao: this should return three rows and there by three names because you have already set up `LIMIT 0, 3` which will return only three rows.
Sarfraz
It will return 3 rows of content, but I need to get 3 names.
Qiao
@Sarfraz, I think Qiao wants possibly many rows (more than 3), but limited to only 3 distinct `name.id`s
unutbu
@Qiao: see my updated answer please.
Sarfraz
+1  A: 
SELECT content.name, content.title
FROM name LEFT JOIN content ON name.id = content.name
LIMIT 0, 3
Salil
+1  A: 

Subquery?

SELECT name.title, content.title
FROM name LEFT JOIN content ON name.id = content.name
WHERE name.id IN (SELECT name.id FROM name LIMIT 3)
Andrew