[英]MYSQL update a row if all multiple rows that belong to the same foreign ID have same value
I have 3 tables: schedule
and locations
, suites
. 我有3张桌子: schedule
和locations
, suites
。
Schedule's structure: schedule-id
, location-id
, schedule-completed-on-date
计划的结构: schedule-id
, location-id
, schedule-completed-on-date
Locations' structure: location-id
, location-building-number
, location-street-name
地点的结构: location-id
, location-building-number
, location-street-name
Suites' structure: suite-id
, location-id
, suite-number
, suite-visited
套房的结构: suite-id
, location-id
, suite-number
, suite-visited
Many suites may belong to same location. 许多套房可能属于同一地点。 Schedule's location-id
is unique, so there may be only one unique location scheduled at any time, no duplicates. Schedule的location-id
是唯一的,因此任何时候可能只有一个唯一的位置,没有重复。
I want to set schedule-completed-date-on
to a date, which I know how to do, if every single suite for a location of a schedule row have suite-visited
equal to 1
( 0- no, 1- yes ). 我想将schedule-completed-date-on
为一个日期,我知道该怎么做,如果一个日程表行位置的每个套件都有suite-visited
等于1
( 0-否,1-是 )。
Is it possible to do with MySQL, and if so then how? 是否可以使用MySQL,如果可以,那么如何? Or do I have to do it programmatically using a server side language? 或者我是否必须使用服务器端语言以编程方式执行此操作?
For example, if I have two locations - 1 Main St., and 2 Main St. - and 10 suites in total - 5 belong to first location, other 5 belong to second location. 例如,如果我有两个位置 - 1个主街和2个主街 - 总共10个套房 - 5个属于第一个位置,其他5个属于第二个位置。 If MySQL detects that all 5 suite rows that relate to first location have suite-visited
equal to 1
, then immediately set schedule-completed-on
to current date, otherwise don't. 如果MySQL检测到与第一个位置相关的所有5个套件行的suite-visited
等于1
,则立即将schedule-completed-on
为当前日期,否则不会。
Data at hand and desired result: 手头的数据和期望的结果:
LOCATIONS
location-id location-building-number location-street-name
1 1 Main St.
2 2 Main St.
SUITES
suite-id location-id suite-number suite-visited
1 1 100 1
2 1 200 0
3 1 300 0
4 1 400 0
5 1 500 1
6 2 1000 1
7 2 1100 1
8 2 1200 1
9 2 1300 1
10 2 1400 1
SCHEDULE
schedule-id location-id schedule-completed-on-date
1 1 NULL
2 2 7/3/2015 00:00:00
// because all suites for location 2 have suite-visited set to 1
// second row under SCHEDULE gets the date set
// because all suites belonging to
// location 2 have been visited
Trigger for auto update of SCHEDULE based on update of suite-visited table, name the trigger appropriately. 基于套件访问表的更新触发SCHEDULE的自动更新,适当地命名触发器。
DELIMITER $$
CREATE TRIGGER trigger_name
AFTER UPDATE
ON suite-visited FOR EACH ROW
BEGIN
IF NOT EXISTS (select 1 from SUITES where suite-visited = 0 and location-id = new.location-id) THEN
UPDATE SCHEDULE set schedule-completed-on-date = curdate() where location-id = new.location-id;
END IF;
END;
$$
DELIMITER ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.