gpt4 book ai didi

php - 如何构建一个查询,通过交易历史提取用户当前拥有的所有合约

转载 作者:行者123 更新时间:2023-11-29 06:35:12 24 4
gpt4 key购买 nike

我正在设置一个脚本,需要通过交易历史记录提取用户拥有的所有当前合约。

这是交易表和一些测试数据:

CREATE TABLE `transaction` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`sender_id` int(11) NOT NULL,
`recipient_id` int(11) NOT NULL,
`contract_id` int(11) NOT NULL,
`created_on` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `sender_id` (`sender_id`,`contract_id`,`tokens`),
KEY `recipient_id` (`recipient_id`,`contract_id`,`tokens`)
);

INSERT INTO `transaction` VALUES
(1,10,20,1,'2019-01-20 15:41:47'),
(2,10,20,2,'2019-01-20 15:41:47'),
(3,30,10,1,'2019-01-20 15:41:47'),
(4,30,10,3,'2019-01-20 15:41:47'),
(5,20,10,2,'2019-01-20 15:41:47');

作为输出,我想要一个包含给定用户的所有合约 ID 的数组。

用户 id = 10 的查询输出:

+-------------+
| contract_id |
+-------------+
| 1 |
+-------------+
| 2 |
+-------------+
| 3 |
+-------------+

这是我当前必须实​​现的代码。不过,如果它是一个查询,那就太好了。

$query = 'SELECT DISTINCT contract_id
FROM transaction
WHERE tokens IS NULL
ORDER BY created_on DESC';

$statement = $this->entityManager
->getConnection()
->prepare($query);

$statement->execute();

$contracts = [];

foreach ($statement->fetchAll() as $row) {
$query = 'SELECT *
FROM transaction
WHERE contract_id = :contract
AND tokens IS NULL
ORDER BY created_on DESC';

$statement = $this->entityManager
->getConnection()
->prepare($query);

$statement->execute([
'contract' => $row['contract_id']
]);

$result = $statement->fetch();

if ((int) $result['recipient_id'] !== $user->getId()) {
continue;
}

$contracts[] = $result['contract_id'];
}

return $contracts;

最佳答案

采用尽可能少的答案,使用DISTINCT来防止输出重复。 ORDER BY 是可选的。

SELECT DISTINCT contract_id
FROM transactions
WHERE recipient_id = :id
ORDER BY contract_id

您的 recipient_id 索引将有助于此查询。

关于php - 如何构建一个查询,通过交易历史提取用户当前拥有的所有合约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com