假设我们有一个tally_sheets
表格,其中包含一些理货单信息,如下面的描述和一个下面描述的persons
表格,其中tally_sheets
包含一个以逗号分隔的理货单 ID 列表的字段。
每个计数表仅包含来自国家/城市组合的人。
如何获取所有统计表的列表,其中包含表中的所有字段tally_sheets
和字段?country
city
persons
mysql> desc tally_sheets;
+-----------+--------------+
| Field | Type |
+-----------+--------------+
| id | int(10) |
| date | char(10) |
| person | varchar(64) |
| comment | varchar(255) |
| timestamp | timestamp |
+-----------+--------------+
mysql> desc persons;
+------------------+--------------+
| Field | Type |
+------------------+--------------+
| id | int(11) |
| name | varchar(30) |
| country | varchar(60) |
| city | varchar(60) |
| tally_sheets | varchar(64) | <== comma separated tally_sheet's ID
+------------------+--------------+
跑步
SELECT ts.id, ts.date, p.country, p.city, ts.person, ts.`comment`, '0' AS sqlExclude
FROM tally_sheets ts
RIGHT JOIN persons p ON ts.id IN (p.tally_sheets)
GROUP BY p.city
将给出所有国家/城市组合,但所有其他字段为NULL
.
+------+------+------------+--------------------+--------+---------+------------+
| id | date | country | city | person | comment | sqlExclude |
+------+------+------------+--------------------+--------+---------+------------+
| NULL | NULL | Country1 | City1 | NULL | NULL | 0 |
| NULL | NULL | Country1 | City2 | NULL | NULL | 0 |
| NULL | NULL | Country2 | City3 | NULL | NULL | 0 |
+------+------+------------+--------------------+--------+---------+------------+
运行SELECT ts.id, p.country, p.city FROM persons p LEFT JOIN tally_sheets ts ON ts.id IN (p.tally_sheets) GROUP BY p.city
也将返回NULL
字段。
+------+------------+--------------------+
| id | country | city |
+------+------------+--------------------+
| NULL | Country1 | City1 |
| NULL | Country1 | City2 |
| NULL | Country2 | City3 |
+------+------------+--------------------+
我做错了什么?非常感谢!