如果您存储不同元素之间的联系人,并且想要消除特定类型的元素并存储由被消除的元素相互连接的元素的新联系人,您可能会遇到以下问题:
想象一下这个问题。您有一个与其他分子接触的水分子(如果接触是氢键,我的水分子周围可以有 4 个其他分子)。就像在下面的图片中一样(A、B、C、D 是其他一些原子,点表示接触)。
A B
| |
H H
. .
O
/ \
H H
. .
C D
您拥有有关所有点的的信息,您需要消除中心的水并创建描述 A-C、A-D、A-B、B-C、B-D 和 C-D 联系的新记录。
2、解决方案
要从 SQLite 中提纯数据并连接多个联系人,可以按照以下步骤操作:
- 创建一个临时视图
hoh_view,其中包含所有氢键(HOH)的供体原子 ID 和受体原子 ID:
create temporary view hoh_view as
select donor_id as id, atoms.id as hoh_id from contacts, atoms
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
where acceptor_id=atoms.id and atoms.amino='HOH'
union select acceptor_id as id, atoms.id as hoh_id from contacts, atoms
where donor_id=atoms.id and atoms.amino='HOH';
- 使用临时视图
hoh_view,查询所有氢键之间的连接:
select a.id, b.id from hoh_view as a, hoh_view as b
where a.id > b.id and a.hoh_id=b.hoh_id;
- 将查询结果与
contacts表连接,以获取有关每个连接的详细信息,例如距离和方向性:
select c.donor_id, c.acceptor_id, c.directness from contacts c
join (
select a.id, b.id from hoh_view as a, hoh_view as b
where a.id > b.id and a.hoh_id=b.hoh_id
) as hoh_connections on c.donor_id = hoh_connections.id or c.acceptor_id = hoh_connections.id;
- 根据需要,对结果进行进一步处理,例如过滤掉不需要的列或添加其他信息。
以下是一个使用 Python 和 SQLite3 库来实现上述解决方案的代码示例:
import sqlite3
# 连接到 SQLite 数据库
conn = sqlite3.connect('contacts.db')
cursor = conn.cursor()
# 创建临时视图 hoh_view
cursor.execute('''
create temporary view hoh_view as
select donor_id as id, atoms.id as hoh_id from contacts, atoms
where acceptor_id=atoms.id and atoms.amino='HOH'
union select acceptor_id as id, atoms.id as hoh_id from contacts, atoms
where donor_id=atoms.id and atoms.amino='HOH';
''')
# 查询所有氢键之间的连接
cursor.execute('''
select a.id, b.id from hoh_view as a, hoh_view as b
where a.id > b.id and a.hoh_id=b.hoh_id;
''')
# 将查询结果与 contacts 表连接
cursor.execute('''
select c.donor_id, c.acceptor_id, c.directness from contacts c
join (
select a.id, b.id from hoh_view as a, hoh_view as b
where a.id > b.id and a.hoh_id=b.hoh_id
) as hoh_connections on c.donor_id = hoh_connections.id or c.acceptor_id = hoh_connections.id;
''')
# 获取查询结果
results = cursor.fetchall()
# 关闭连接
cursor.close()
conn.close()
# 打印查询结果
for result in results:
print(result)
这个代码示例将连接所有氢键之间的联系人,并打印出每个联系的供体原子 ID、受体原子 ID 和方向性。