【问题标题】:MySQL SELECT DISTINCT field from second table using a relationship [duplicate]MySQL 使用关系从第二个表中选择 DISTINCT 字段[重复]
【发布时间】:2014-12-18 02:57:26
【问题描述】:

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

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

如何从tally_sheetscountrycity 表中获取所有字段的所有计数表列表?

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              |
+------+------------+--------------------+

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

【问题讨论】:

  • 规范化你的架构,不要使用逗号分隔的列表。
  • @Barmar,我不能碰任何桌子。谢谢提示。

标签: mysql join distinct find-in-set


【解决方案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 如何标准化你的结构

【讨论】:

  • 无法触摸表格结构。您的代码工作正常,但它返回所有人的列表。添加GROUP BY p.country, p.city 将返回所有计数表。谢谢!
猜你喜欢
  • 2017-09-05
  • 2013-04-13
  • 1970-01-01
  • 2011-11-25
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多