使用关系从第二个表中选择MySQL SELECT DISTINCT字段

时间:2014-10-22 15:26:42

标签: mysql join distinct find-in-set

假设我们有一个tally_sheets表,其中包含一些计数表信息,如下面的说明和下面描述的persons表,其中tally_sheets字段包含计数表ID的列表用逗号分隔。

每个计数表仅包含来自国家/城市组合的人。

如何从tally_sheets表中的countrycity以及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              |
+------+------------+--------------------+

我做错了什么?非常感谢!

1 个答案:

答案 0 :(得分:1)

首先,我会说你应该规范你的架构并阅读Database_normalization来处理关系,如果你无法改变你的架构,你可以使用find_in_setin()不适用于存储在列

中的逗号分隔列表
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如何规范化您的结构