mysql组\u concat不在

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

我还没有找到一个类似的问题和一个我可以使用的答案,希望我没有忽视另一个。
我想构建一个查询,返回值不在组中的项。让我举个例子:
我有一张练习表:

id  |  ExerciseName
---------------------
1   |  Squat
2   |  Deadlift
3   |  Bench Press
4   |  Deadlift Hex Bar

然后我有一个单独的表格,显示了每种设备的用途:

id  | ExerciseId  |  EquipmentId
---------------------------------
1   | 1           | 1
2   | 1           | 20
3   | 2           | 1
4   | 3           | 47

然后我有一个单独的表格,显示每个设备的名称:

id  | name_en
-------------
1   | Barbell
2   | Squat Rack
3   | Dumbbell

现在,我有一个查询,我正在运行,可以选择演习,我想查询演习,其中设备可供用户使用。假设用户没有id=1的设备。那么我只想返回练习3。目前,在我的查询中,我得到了练习1和练习3,它之所以这样做是因为练习1的设备id=1,但是它还有一个不等于设备id=1的设备id=20。

SELECT
    we.id ExerciseId,
    we.name_en ExerciseName
    GROUP_CONCAT(DISTINCT weeq.name_en ORDER BY weeq.name_en SEPARATOR ', ') Equipment
    FROM workouts_exercise we
JOIN workouts_exercise_equipment weeq ON weeq.exercise_id = we.id
JOIN workouts_equipment weq ON weq.id = weeq.equipment_id
WHERE weq.id NOT IN ("1")
GROUP BY we.id

如前所述,其结果如下:

ExerciseId  | ExerciseName   | Equipment
------------------------------------------
1           | Squat          | 20
3           | Bench Press    | 47

实际上,我想要的是:

ExerciseId  | ExerciseName   | Equipment
------------------------------------------
3           | Bench Press    | 47
h5qlskok

h5qlskok1#

你想排除需要装备1的练习。你可以用 NOT IN 或者 NOT EXISTS 为此:

select weeq.exerciseid, we.exercisename, weq.name_en as equipment
from workouts_exercise we
join workouts_exercise_equipment weeq on weeq.exerciseid = we.id
join workouts_equipment weq on weq.id = weeq.equipmentid
where we.id not in
(
  select exerciseid from workouts_exercise_equipment where equipmentid = 1
)
nxowjjhe

nxowjjhe2#

一种方法是使用反连接来过滤使用一个或多个要排除的设备的练习:

SELECT
    we1.ExerciseId,
    ex.ExerciseName,
    we1.EquipmentId AS Equipment
FROM workouts_equipment we1
LEFT JOIN workouts_equipment we2
    ON we1.ExerciseId = we2.ExerciseId AND
       we2.EquipmentId IN (1)
INNER JOIN workouts_exercise ex
    ON we1.ExerciseId = ex.id
WHERE
    we2.ExerciseId IS NULL;

演示

相关问题