假设我们有一个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 |
+------+------------+--------------------+
我做错了什么?非常感谢!
答案 0 :(得分:1)
首先,我会说你应该规范你的架构并阅读Database_normalization
来处理关系,如果你无法改变你的架构,你可以使用find_in_set
,in()
不适用于存储在列
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 find_in_set(ts.id ,p.tally_sheets) >0
以下reference answer如何规范化您的结构