首页 > 解决方案 > 从 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

标签: mysql

解决方案


答案由@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))

推荐阅读