dongqiang4986 2015-07-07 23:15
浏览 41
已采纳

MYSQL:一列上有多个“矛盾”的条件

I'm trying to create a query that ONLY outputs members if they meet 2 conditions.

The first condition: If the user has a matching "courseID".

The second condition: If the user doesn't have a matching "courseID".

Obviously this is contradicting so let me explain.

I have two tables...

members

  • ID
  • email

certifications

  • ID
  • memberID
  • courseID

When members complete a course they gain a certification. The certification stores their memberID and the courseID. Members can have multiple certifications.

The end goal is to create an email sending list to promote courses.

Let's say we have two courses. "Beginner"(courseID=1) and "Intermediate"(courseID=2).

One member could have both certifications, one for each course. Another member could just have the one, the "Beginner" certification.

I want to send a promotional email to all members who have the "Beginner" certification. However I want to exclude any members with the "Intermediate" certification.

The problem I can't seem to overcome is how to exclude the members with the "Intermediate" certification.

**I have simplified this example, in truth there is a vast amount of different certification types **

Below is a rough query I've been trying... I've tried so, so many different queries.

Any help would be great, thank you.

// Look Up Recipients
$recipientsQuery = $wpdb->get_results("
SELECT DISTINCT(email) 
FROM $memberTable
LEFT JOIN $certificationsTable
ON $memberTable.ID = $certificationsTable.memberID
WHERE courseID = 4 AND courseID != 5
");
  • 写回答

2条回答 默认 最新

  • duanpang5583 2015-07-07 23:20
    关注
    SELECT m.ID, m.email
       , MAX(IF(c.courseID = 4, 1, 0)) AS hasCourse4
       , MAX(IF(c.courseID = 5, 1, 0)) AS hasCourse5
    FROM members AS m 
    LEFT JOIN certifications AS c ON m.ID = c.memberID
    HAVING hasCourse4 = 1 AND hasCourse5 = 0
    ;
    

    Alternatively, you could join certs to members to certs, this might be faster:

    SELECT m.email
    FROM certifications AS c1
    INNER JOIN members AS m ON c1.memberID = m.ID
    LEFT JOIN certifications AS c2 ON m.ID = c2.memberID AND c2.courseID = 5
    WHERE c1.courseID = 4 AND c2.courseID IS NULL
    ;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题