Search code examples
mysqlsqldatabaseinner-join

Why doesn't this SQL statement work


I have two tables. Job and Location. I then want to query the database to get jobs that are in a certain location. Here are my database tables.

CREATE TABLE `job` (
  `id` int(11) NOT NULL,
  `title` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `company_id` int(11) NOT NULL,
  `contact_email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `contact_telephone` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `is_active` tinyint(4) NOT NULL,
  `salary_id` int(11) NOT NULL,
  `salary` int(11) NOT NULL,
  `tenure_id` int(11) NOT NULL,
  `work_type_id` int(11) NOT NULL,
  `occupation_id` int(11) NOT NULL,
  `location_id` int(11) NOT NULL,
  `views` int(11) NOT NULL,
  `img_url` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

AND

CREATE TABLE `location` (
  `id` int(11) NOT NULL,
  `region` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `state` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Why doesn't this query create an inner join between job and location?

SELECT * FROM job, location 
WHERE location.region = 'Central Coast' 
OR location.region = 'Hunter Valley' 
OR location.region = 'Illawarra' 
AND job.location_id = location.id

Solution

  • Because and has a higher precedence than or.

    This means your where clause is executed as:

    WHERE  location.region = 'Central Coast' 
           OR location.region = 'Hunter Valley' 
           OR (location.region = 'Illawarra' AND job.location_id = location.id)