mysql - SQL - 选择与 3 个组合条件中的几个匹配的值
问题描述
在尝试解决这个问题并没有成功地在网上搜索答案后,我辞职寻求帮助 - 所以任何人都将不胜感激!
我有一个具有以下结构的 SQL 表:
+--------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+----------------+
| id | int(25) | NO | PRI | NULL | auto_increment |
| municipality | varchar(50) | NO | MUL | NULL | |
| admin | varchar(50) | NO | | NULL | |
| country | varchar(50) | NO | | NULL | |
| longitude | varchar(50) | NO | | NULL | |
| latitude | varchar(50) | NO | | NULL | |
+--------------+-------------+------+-----+---------+----------------+
我希望选择该表的一个子集,其中满足几个三元组条件,例如:
municipality = 'New York', admin = 'New York', country = 'United States'
。我希望这样做并选择不仅municipality
因为有时在不同的行政区域中存在相同的地名。
这是我迄今为止尝试过的:
SELECT * FROM locations WHERE (municipality, admin, country) IN
('Pearl River', 'New York', 'United States'),
('Shelton', 'Washington', 'United States'),
('Granite', 'Illinois', 'United States'),
('Washington', 'Pennsylvania', 'United States'),
('Erlanger', 'Kentucky', 'United States'),
('Warren', 'Ohio', 'United States');
也:
SELECT * FROM locations WHERE municipality IN ('Pearl River', 'Shelton', 'Granite', 'Washington', 'Erlanger', 'Warren')
AND WHERE admin IN ('New York', 'Washington', 'Illinois', 'Pennsylvania', 'Kentucky', 'Ohio')
AND WHERE country IN ('United States', 'United States', 'United States', 'United States', 'United States', 'United States');
但两个查询都只返回这个标准错误:could not run statement: You have an error in your SQL syntax;
我真的希望有人可以帮助我解决这个问题,非常感谢!
解决方案
您应该用括号将您匹配的元组列表括起来,并在它们前面加上“VALUES”。例如,
SELECT * FROM locations WHERE (municipality, admin, country) IN (
VALUES
('Pearl River', 'New York', 'United States'),
('Pearl', 'New York', 'United States'),
('Athens', 'Georgia', 'United States')
);
我认为,我已经针对具有以下结构的 sqlite 数据库对此进行了测试,并获得了正确的输出。
CREATE TABLE locations (municipality TEXT, admin TEXT, country TEXT);
INSERT INTO locations VALUES('Pearl River','New York','United States');
INSERT INTO locations VALUES('Pearl River','Alabama','United States');
INSERT INTO locations VALUES('Athens','Georgia','United States');
返回以下内容:
Pearl River|New York|United States
Athens|Georgia|United States
-- 忍者编辑 --
请注意,上述查询在 SQLite 中有效,但在 MySQL 中无效。要使这个查询适用于 MySQL,只需删除“VALUES”关键字,但在元组列表周围保留括号是至关重要的。例如,
SELECT * FROM locations WHERE (municipality, admin, country) IN (
('Pearl River', 'New York', 'United States'),
('Pearl', 'New York', 'United States'),
('Athens', 'Georgia', 'United States')
);
推荐阅读
- excel - VBA excel参考用户表单作为变量来获取数据
- protocol-buffers - 如何在 protobuffer 中使用反射设置消息的扩展字段
- node.js - 如何获取文件夹中最近的图像?
- php - PHP-Unable get values from $_SESSION, error msg is Notice: Undefined variable: _SESSION
- javascript - 如何循环数字序列以根据给定数字连续推送?(斐波那契)
- javascript - 如何从输入字符串中使用javascript中的子字符串方法?
- javascript - MongoDB 通过 findOne 加入集合
- prolog - 如何在prolog中打印出所有事实
- php - Laravel 日期/时间比较
- c# - 文本框中的特定字符