如何使用两列来确定是否将值插入另一个表?

时间:2014-04-08 23:55:39

标签: php sql select if-statement

如何通过评估SQL中不同表中的其他两列来确定是否允许INSERT INTO表?

e.g。类似的东西:

IF (
    (SELECT members_schoolid FROM members WHERE members_id=1) = 
    (SELECT events_schoolid FROM events WHERE events_eventid=10)
) 
THEN 
    INSERT INTO schedules (schedules_userid, schedules_eventid) VALUES (1, 10)

如果他/她属于创建该活动的同一所学校,则应允许学生将活动插入他/她的日程表,例如如果members_schoolid = events_schoolid

谢谢!

1 个答案:

答案 0 :(得分:0)

怎么样:

INSERT INTO schedules (schedules_userid, schedules_eventid)
SELECT 1, 10
WHERE EXISTS (
  SELECT * 
  FROM members, events 
  WHERE members.members_schoolid=events.events_schoolid 
    AND events.events_eventid=10 
    AND members.members_id=1
)

运行此查询时,内部部件将作为查询运行。如果它返回任何行(exists),那么您的插入将运行。