If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > MySQL Query to find available premises

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-25-05, 22:13
squire squire is offline
Registered User
 
Join Date: Jan 2005
Posts: 7
Question MySQL Query to find available premises

Hi guys,

I have a problem with a MySQL query. I have two tables, shown below:

Table 1: PREMISES
prem_id
address
size
price

Table 2: TENANTS
ten_id
name
type
description
prem_id

I am trying to do a query that will find any premises that are NOT occupied by a tenant.

I was using this code:

Code:
select p1.address, p1.size, p1.price FROM premises AS p1, 
tenants AS p2 WHERE p1.prem_id != p2.prem_id
BUT this displays all the premises that are not the same as the prem_id in the tenants table and does this for each tenant creating duplicated results.

Can anyone help me fix this query?

Thanks in advance.

Last edited by squire; 01-26-05 at 12:59.
Reply With Quote
  #2 (permalink)  
Old 01-25-05, 23:38
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
you need a LEFT OUTER JOIN looking for unmatched rows (null in the right table join field)

yes, i realize it looks weird the first time you see it
Code:
select p1.address
     , p1.size
     , p1.price 
  FROM premises AS p1
left outer
  join tenants AS p2 
    on p1.prem_id 
     = p2.prem_id
 where p2.prem_id is null
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 01-26-05, 06:29
squire squire is offline
Registered User
 
Join Date: Jan 2005
Posts: 7
Thumbs up

Hi r937,

THANK YOU very much. Your code worked perfectly! I have been learning SQL and was thinking it may have something to do with joins but I have no proper knowledge of how to use them. This will help me greatly.

Thank you again.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On