【发布时间】:2021-10-10 21:51:40
【问题描述】:
我正在尝试针对我无法控制的数据库构建一个 sqlite 查询,即我无法更改当前存储数据的奇怪方式。
我的数据分布在多个表中,其中一个特别是给我带来了问题;联系人。
我感兴趣的表格结构如下(示例仅包括我关心的);
结果
| id | state | account |
|---|---|---|
| 5 | 0 | 102 |
| 11 | 2 | 62 |
数据
| id | results_id | type | date | contact_id |
|---|---|---|---|---|
| 1 | 5 | 1033 | 1596664666 | 360 |
| 2 | 11 | 1034 | 1596452446 | 32 |
联系人列表
| id | contact_id | key | type |
|---|---|---|---|
| 32 | 12 | test | |
| 360 | 110 | test2 | |
| 360 | 5 | test2 | phone |
联系人
| id | results_id | name | |
|---|---|---|---|
| 12 | 231 | Test Account | test1@gmail.com |
| 110 | 726 | Test Account 2 | test2@gmail.com |
| 5 | 6 | Test Account no | 01234567890 |
所以我想做的是:
- 查询数据表以获取该表中的所有值,从相关表中查找类型。
- 加入结果表 (Data.results_id = Results.id) 并查找相关帐户和状态详细信息
- 从联系人表中获取联系人姓名和电子邮件。
最后一点是什么让我失望。 Data.contact_id = Contacts_list.id 然后是 Contacts_list.contact_id = Contacts.id
如果我在 Contacts_list 上进行左连接,我会得到额外的行,因为 Contacts_list 可以有多个相同 ID 的行,而我只需要与 Data 表一样多的行。我想要的是将多个联系人连接到一个单元格中,例如;
| account | state | type | date | contact |
|---|---|---|---|---|
| 102 | 0 | 1033 | 1596664666 | Test Account (test1@gmail.com) |
| 62 | 2 | 1034 | 1596452446 | Test Account 2 (test2@gmail.com), Test Account no (01234567890) |
我觉得会有一个简单的解决方案,但我现在摸不着头脑......有什么想法吗?
【问题讨论】: