为什么这个sql语句不能工作

agyaoht7  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(320)

我有两张table。工作和地点。然后,我想查询数据库以获取位于某个位置的作业。这是我的数据库表。

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;

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;

为什么这个查询不在job和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
aemubtdh

aemubtdh1#

因为 and 优先级高于 or .
这意味着你的 where 条款执行为:

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

dzjeubhm2#

切换到现代,明确 JOIN 语法,因为它更容易写(没有错误),更容易读(和维护),并且如果需要的话更容易转换为外部连接。
使用 IN :

SELECT *
FROM job
JOIN location ON job.location_id = location.id
WHERE location.region IN ('Central Coast', 'Hunter Valley', 'llawarra')

相关问题