简体   繁体   English

MYSQL:从多对多链接表中选择

[英]MYSQL: select from many-to-many linking table

I have 3 tables: 我有3张桌子:

1) exercise: exercise_id, name 1)练习:exercise_id,名称

2) equipment: equipment_id, name 2)设备:equipment_id,名称

3) exercise_equipment: exercise_id, equipment_id - this is the linking table between exercise and equipment. 3)exercise_equipment:exercise_id,device_id-这是运动与设备之间的链接表。 In this table, one exercise can require multiple pieces of equipment, and the same equipment can be used for many exercises. 在此表中,一项练习可能需要多件设备,并且同一设备可用于许多练习。

CREATE TABLE exercise
    (`ex_id` int, `name` varchar(30))
;   
INSERT INTO exercise
    (`ex_id`, `name`)
VALUES
    (1, 'push ups'),
    (2, 'sit ups'),
    (3, 'squats'),
    (4, 'push ups with a fitness ball')
;

CREATE TABLE equipment
    (`eq_id` int, `name` varchar(30))
;
INSERT INTO equipment
    (`eq_id`, `name`)
VALUES
    (1, 'none'),
    (2, 'mat'),
    (3, 'ball')
;

CREATE TABLE exercise_equipment
    (`ex_id` int, `eq_id` int)
;
INSERT INTO exercise_equipment
    (`ex_id`, `eq_id`)
VALUES
    (1, 2),
    (2, 2),
    (3, 1),
    (4, 2),
    (4, 3)
;

What I need to do is select all the exercises that the user can do with the equipment that he has (for example, 1 and 2 - no equipment or mat). 我需要做的是选择用户可以使用其拥有的设备(例如1和2-没有设备或垫子)进行的所有练习。

I have found some examples and tried the following queries with inner join and where in: 我找到了一些示例,并尝试了以下查询以及内部联接以及其中的位置:

SELECT ex.ex_id, ex.name from exercise ex 
LEFT JOIN exercise_equipment exeq ON ex.ex_id = exeq.ex_id 
WHERE exeq.eq_id IN (1,2);

and

select ex_id, name from exercise 
where ex_id in (select ex_id from exercise_equipment where eq_id in (1,2));

But they return all exercises, instead of just the first three. 但是他们返回所有练习,而不仅仅是前三个。 In this case, if the user wants to do exercises that require no equipment or a mat (1 and 2), I want push ups, sit ups, and squats to be returned, but not the mat exercise with a ball. 在这种情况下,如果用户想要进行不需要任何设备或垫子(1和2)的运动,我希望将俯卧撑,仰卧起坐和下蹲恢复原状,而不是使用球进行垫子运动。

I hope my explanation is clear. 希望我的解释清楚。 I would really appreciate any help I can get! 我会很感激我能得到的任何帮助!

You want exercises that use only 1 and 2. When you use a WHERE clause, you are filtering out all the other equipment, so that won't work. 你要当您使用一个使用1和2的练习WHERE子句,你过滤掉所有其他设备,所以这是行不通的。

Instead, you need to aggregate and check that no other equipment is being used for the entire exercise. 相反,您需要汇总并检查整个练习中是否没有使用其他设备。 This is a similar query, with a HAVING clause: 这是一个类似的查询,带有HAVING子句:

SELECT ex.ex_id, ex.name
FROM exercise ex LEFT JOIN
     exercise_equipment exeq
     ON ex.ex_id = exeq.ex_id 
GROUP BY ex.ex_id, ex.name
HAVING SUM(exeq.eq_id NOT IN (1, 2)) = 0;

In the event that some exercises have no equipment at all, you might want: 如果某些练习根本没有设备,您可能需要:

HAVING COALESCE(SUM(exeq.eq_id NOT IN (1, 2)), 0) = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM