简体   繁体   English

带有多个表联接的mysql查询从一个表中获取不包括匹配条件的数据

[英]mysql query with multiple table joins to fetch data excluding a matching condition from one table

Looking for some help on mysql query for joining table to extract the data. 寻找有关mysql查询的帮助,以联接表以提取数据。

I have two main tables, 我有两个主表,

  1. session_schedule -> all schedules here entries: session_schedule->所有时间表都在这里输入:

    40, 40岁

    41, 41,

    42 42

  2. session_booking. session_booking。 -> all enrollments here with student_id ->所有的学生编号都在此处

    40 - me 40-我

    40 - my friend 40-我的朋友

    41 - my friend 41-我的朋友

    42 - none 42-无

When a user enrolls for a schedule from the session_schedule, this gets populated in the session_booking table. 当用户从session_schedule中注册时间表时,会在session_booking表中填充该时间表。 Now I want to fetch all schedules which are not enrolled by me. 现在,我想获取所有未注册的时间表。

Please see the following code. 请参见以下代码。

This should address the following cases: 这应该解决以下情况:

  1. sessions not enrolled by anyone. 没有任何人注册的会话。

  2. sessions enrolled by others , but not by me. 其他人参加的会议,但不是我参加的会议。

Its failing the second case, where its picking up session enrolled by me and others. 它在第二种情况下不及格,我和其他人参加了它的接听环节。

I am getting all three entries.. 40, 41, 42. 我得到了所有三个条目。40、41、42。
I should not be getting 40 我不应该得到40

Please see the following code. 请参见以下代码。

 $session_schedule = ORM::factory('sessionschedule')->select(
    'sessionschedule.session_id' ,
    'sessions_booking.session_id' ,
    'sessions_booking.student_id', ) 



 ->join('sessions_booking','LEFT')  
 // this join is to exclude already paid sessions by the user                   
 ->on('sessionschedule.id','=','sessions_booking.session_id') 
 ->where('sessionschedule.session_id', '=', $_POST['id'] )
 ->where_open()
 ->where('sessions_booking.session_id','=',NULL) // for sessions nobody booked                                          
 ->or_where('sessions_booking.student_id','!=',$user->id  )// for sessions booked by others             
 ->where_close()    

 ->group_by('sessionschedule.id')->find_all();

Try this: 尝试这个:

SELECT ses.* 
FROM session_schedule ses 
LEFT JOIN session_booking sb ON ses.id=sb.session_id AND sb.student_id='me' 
WHERE sb.session_id IS NULL;

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

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