简体   繁体   中英

Filtering on a one-to-many relationship in MySQL

I have a question regarding filtering in MySQL. I have two tables one with members and one with membership data. I like to be able to join the two tables and be able to filter on:

  • members that still have an active membership (date of October 6th 2020 as reference date)
  • memebers that do not have an active membership anymore

Can anyone give me the correct SQL code the filter on this? I am not realy good in this more advanced SQL statements. Many thanks in advance!

Members

+----+------------+
| ID |   Name     |
+----+------------+
| 01 | Gerico     |
| 02 | Stefan     |
+----+------------+

Membership

+----+------------+-------------+------------+
| ID | MemberID   | From        | To         |
+----+------------+-------------+------------+
| 01 |         01 | 01/01/1990  | 01/01/2000 |
| 02 |         01 | 01/01/2005  | 31/12/2154 |
| 03 |         02 | 01/01/1990  | 01/01/2000 |
| 04 |         02 | 01/01/1992  | 31/12/1999 |
+----+------------+-------------+------------+

I am assuming an active member is one who has a membership whose date range includes the current date. Then to select active members:

SELECT DISTINCT Members.* FROM
Members JOIN Membership ON Members.ID = Membership.MemberID
WHERE CURDATE() BETWEEN Membership.`From` AND Membership.`To`

(A SELECT DISTINCT is done in case a member has multiple, overlapping memberships.)

Or you can use:

SELECT * FROM Members
WHERE EXISTS (
    SELECT ID FROM Membership WHERE CURDATE() BETWEEN `From` AND `To` AND MemberID = Members.ID
)

To select non-active members:

SELECT * FROM Members
WHERE NOT EXISTS (
    SELECT ID FROM Membership WHERE CURDATE() BETWEEN `From` AND `To` AND MemberID = Members.ID
)

See db-fiddle

The comment made by @Strawberry refers to the responsibility of the OP to create the above db-fiddle or equivalent for people to be able to test against us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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