shwebdev
shwebdev

Reputation: 103

Two tables into 1 SQL Query

I am showing some listings on a page by location using the following query:

SELECT *,
 ((ACOS(SIN($lat * PI() / 180) * SIN(gps_lat * PI() / 180) + COS($lat * PI() / 180) * COS(gps_lat * PI() / 180) * COS(($lon - gps_long) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance 
  FROM listings

I would like to now also filter the above listings by their building type. A separate table records the listing id and the building type id as below:

SELECT * 
  FROM building_types_listings 
 WHERE listing_id = listings.id 
   AND building_type_id = '$building_type'

How can I incorporate both queries into one SQL statement?

Upvotes: 0

Views: 104

Answers (1)

Miguel Pérez
Miguel Pérez

Reputation: 506

Try something like:

SELECT whatever fields you need,
       ((ACOS(SIN($lat * PI() / 180) * SIN(gps_lat * PI() / 180) + COS($lat * PI() / 180) * COS(gps_lat * PI() / 180) * COS(($lon - gps_long) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance
FROM listings
  JOIN building_types_listings
    ON listings.id = building_types_listings.listing_id
WHERE building_type_id = '$building_type'

However, you definitely want to rethink how you're building your queries and inserting strings into them. What would happen if $building_type is exactly (minus double quotes) "';DELETE FROM listings;-- "? I recommend you rely on some sprintf-like facility (in PHP it often means you'll need prepared statements) rather than the deprecated misfeature magic quotes.

Upvotes: 1

Related Questions