我在MySQL数据库中有这2个表:
from flask import jsonify
@app.route('/login/')
def login():
return jsonify({"url": "https://www.google.com/"})
基本上,在transaction_status_history中,我将具有一个或多个相同ID_TRANSACTION的记录。
基于以下简单查询,我想针对不同情况设置一些条件:
简单查询:
CREATE TABLE transaction (
ID_TRANSACTION bigint(20) NOT NULL AUTO_INCREMENT,
IND_STATUS varchar(20) NOT NULL,
DAT_CREATION timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
DAT_UPDATE timestamp(3) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(3),
PRIMARY KEY (IDT_TRANSACTION)
) ENGINE=InnoDB;
CREATE TABLE transaction_status_history (
ID_TRANSACTION_STATUS_HISTORY bigint(20) NOT NULL AUTO_INCREMENT,
ID_TRANSACTION bigint(20) NOT NULL,
IND_STATUS varchar(20) NOT NULL COMMENT '(New, Approved, Rejected, Error).',
DAT_CREATION timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (IDT_TRANSACTION_STATUS_HISTORY),
KEY transaction_transtathist_fk (IDT_TRANSACTION),
CONSTRAINT trans_fk FOREIGN KEY (IDT_TRANSACTION) REFERENCES transaction (IDT_TRANSACTION) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
如果对此查询有IND_STATUS ='New'的行和IND_STATUS ='Approved'的另一行 我的查询必须从IND_STATUS ='New'的行中返回ID_TRANSACTION_STATUS_HISTORY。
如果对此查询有IND_STATUS ='Rejected'的行和IND_STATUS ='New'的另一行 我的查询必须从两条记录中返回ID_TRANSACTION_STATUS_HISTORY。
如何在单个查询中执行此逻辑?
答案 0 :(得分:0)
如果您将表保留为其自身,则可以检查“已批准” IND_STATUS。您可以做一些进一步的逻辑假设,例如我们将始终返回“新”记录,并且如果存在的话,我们总是希望返回“已拒绝”记录。除非您没有告诉我们更多的业务需求,否则可以通过以下查询来实现:
SELECT t.IND_STATUS
FROM transaction_status_history t
LEFT JOIN transaction_status_history t1 ON t.idt_transaction = t1.idt_transaction
AND t1.IND_STATUS = 'Approved'
WHERE
t.idt_transaction = 12
AND (
(t.IND_STATUS = 'New' AND ISNULL(t1.IND_STATUS,'Approved') = 'Approved')
OR t.IND_STATUS = 'Rejected'
)