Answer the question
In order to leave comments, you need to log in
How to implement a foreign key in such a situation?
Hey!
There is a table where the receipt and expenditure of money to the account are recorded.
transaction(id, type, sum, date)
service_pay(service_id, transaction_id)
check contrains
Or do you still have to record income and expenses in separate tables?
Answer the question
In order to leave comments, you need to log in
what hinders to create one table?
transaction(id, service_id, type, sum, date, and here the column of the amount of income is with a plus sign, and the amount of expense will be with a minus sign)
Make the service_pay table definition like this:
create table service_pay
(
service_id ...,
transaction_id ... CHECK (transaction_id in (select id from transaction_table where type = ...)) #тип расходной транзакции
foreign key (transaction_id) references transaction(id)
);
DELIMITER //
CREATE TRIGGER service_pay_bi
BEFORE INSERT ON service_pay
FOR EACH ROW
BEGIN
IF NEW.transaction_id IN (SELECT id FROM transaction_table WHERE type = ...) THEN #указать значение события дохода
@last_error = "service_pay table can hold only the payment transactions";
CALL non_existent(); #единственный способ прервать операцию
END IF;
END//
SELECT ...
FROM tbl_1
UNION
SELECT ...
FROM tbl_2;
It seems to me that the simplest thing is to add the TYPE field to the SERVICE_PAY table, and rename the table itself to SERVICE_TRANSACTIONS, immediately laying down the future and implying that not only the client can pay for services, but also services can return money to him or pay rewards, it's just that this feature is in the first version not implemented yet .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question