mysql - 从 id 列表中查询表
问题描述
我正在寻找一种从 Mysql 中的 ID 列表中查询表的方法。我有一个在 postgres 和 SQL Server 中工作的查询,如下所示:
SELECT a.vehicle_id, a.make, a.model, b.id as people_id, b.name as owner
FROM (values (6,3),(7,3),(3,4),(4,2)) as jt (vehicle_id, people_id)
JOIN vehicles a ON (a.vehicle_id = jt.vehicle_id AND a.people_id = jt.people_id)
JOIN people b ON (b.id = v.people_id)
所以我有一个与vehicle_id 和people_id 相同的id 数组。我想知道是否有办法在 MySQL 中执行此操作,或者我是否需要转换 ID 并将它们添加到 where 子句?看起来像这样可能会变得非常可怕:WHERE (a.vehicle_id = 3 AND a.people_id = 4) OR (a.vehicle_id = 4 AND a.people_id = 2) OR … etc
解决方案
答案由@Strawberry 提供。这一个很好地解决了这个问题!将 ID 分配给 where 子句中的字段:
SELECT a.vehicle_id, a.make, a.model, b.id as people_id, b.name as owner
FROM vehicles a
JOIN people b ON (b.id = a.people_id)
WHERE (vehicle_id, people_id) IN ((6,3),(7,3),(3,4),(4,2))
推荐阅读
- javascript - 如何清除间隔?
- django - 我可以在课堂上使用信号接收器吗
- android - 找不到 com.android.tools.build:gradle:4.0.1 (或任何版本)
- ansible - Ansible - 获取组特定的子组
- python - 10 000 不是 Google 搜索引擎中查询的限制吗?
- google-cloud-platform - 在主题之间移动 Google Pub/Sub 消息
- r - 使用循环或应用根据条件仅覆盖数据框中变量的某些值
- bash - 使用 samtools 提取两个伴侣都未映射的未映射读取?
- php - 如何直接在控制台中运行 php 命令?
- javascript - 使用“beforeunload”/“unload”事件监听器关闭浏览器后使用 Fetch 发送 POST 请求不起作用