3

this is the first time I'm dabbling in Databases and was wondering if it was possible to do the following: I have two tables

student (id, name, phone)
photos  (id, student_id, photo)

I wanted to retrieve the student phone who's name is say 'Tom' but only if he has a photo. Is it possible at all to have a condition like this?

Many thanks

1
  • 1
    You need to read up on joins. Commented Nov 11, 2011 at 1:17

4 Answers 4

3
select s.phone from student s 
inner join photos p 
on p.student_id=s.id
where p.photo is not null
Sign up to request clarification or add additional context in comments.

4 Comments

@bryanmac: Assuming that photos.photo is nullable.
@ypercube: Can't that be inferred from the question? only if it has a photo...
@Icarus: It's from student, not students. You also need the where name = 'Tom'.
Infered? No. I would assume that a user has a photo if there is a row in table photos with his id. But adding where p.photo is not null doesn't hurt in either case.
0

That is called an INNER JOIN.

select top 1 name from student s 
inner join photos p
on s.id = p.student_id
where name like 'Tom'

Comments

0

In this case, you can use a join. Try this:

SELECT student.phone
FROM students
INNER JOIN photos
ON student.id=photos.student_id
WHERE student.name LIKE 'Tom'

Comments

0

Yes. Using EXISTS:

SELECT phone
FROM student
WHERE name = 'Tom'
  AND EXISTS
      ( SELECT *
        FROM photos
        WHERE photos.student_id = student.id
      )

or using JOIN. You need to use either DISTINCT or GROUP BY so you don't get the same phone 20 times if the user has 20 photos:

SELECT DISTINCT student.phone
FROM student
  JOIN photos
    ON photos.student_id = student.id
WHERE student.name = 'Tom'

4 Comments

Should be an inner join imo, which does away with the need for a DISTINCT, let the app select which photo to display. Also I think you meant 'same photo 20'.
No, I meant same phone. We have SELECT phone, not SELECT photo.
Also: INNER JOIN is the same as JOIN. Neither gets away with the need for DISTINCT, if we want to display only phone and not phone+photos.
Ahhh my bad. For some reason I thought JOIN was a LEFT JOIN.

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.