tibberous Posted January 2, 2008 Share Posted January 2, 2008 I have two tables, one called users and one called contact. They both have a field called id, with a one to one relationship. Ex: Users: id Name 6 Trent Contact: id PhoneNumber 6 555-555-5555 I want to make a select query to grab the name with the id of 6, and the phone number with the id of 6, but I forget how. Can someone help me out? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/84137-solved-querying-from-two-tables-at-once/ Share on other sites More sharing options...
Renlok Posted January 2, 2008 Share Posted January 2, 2008 SELECT u.Name, c.PhoneNumber FROM users u LEFT JOIN contact ON ( u.id = c.id ) WHERE id = 6 this will join the two tables and pull out the persons name and their phone number Quote Link to comment https://forums.phpfreaks.com/topic/84137-solved-querying-from-two-tables-at-once/#findComment-428297 Share on other sites More sharing options...
aschk Posted January 2, 2008 Share Posted January 2, 2008 If they have a 1-to-1 relationship why are they in 2 tables? p.s. i know what you're going to say, i just want to hear you say it... Quote Link to comment https://forums.phpfreaks.com/topic/84137-solved-querying-from-two-tables-at-once/#findComment-428300 Share on other sites More sharing options...
tibberous Posted January 2, 2008 Author Share Posted January 2, 2008 Just to organize it more, and because the contact data isn't used very often. That worked, thanks. Isn't there also a way to do it with subqueries? I'm trying to get better at mysql, since for a long time I have just used the minimum statements and done all the processing with PHP. Quote Link to comment https://forums.phpfreaks.com/topic/84137-solved-querying-from-two-tables-at-once/#findComment-428319 Share on other sites More sharing options...
aschk Posted January 2, 2008 Share Posted January 2, 2008 You could do it with a subquery, but it's much of a muchness and you're probably better off with a LEFT JOIN purely for presentational purposes. Here is your subquery: SELECT u.Name as Name , (SELECT c.PhoneNumber FROM contact c WHERE c.id=u.id) as PhoneNumber FROM users u WHERE id = 6 Quote Link to comment https://forums.phpfreaks.com/topic/84137-solved-querying-from-two-tables-at-once/#findComment-428323 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.