我想要合并三个表。
我要运行以下查询:
DROP TABLE
IF EXISTS testgiver.smart_curmonth_downs;
CREATE TABLE testgiver.smart_curmonth_downs
SELECT
ldap_karen.uid,
ldap_karen.supemail,
ldap_karen.regionname,
smart_curmonth_downs_raw.username,
smart_curmonth_downs_raw.email,
smart_curmonth_downs_raw.publisher,
smart_curmonth_downs_raw.itemtitle,
smart_items.`Owner`
FROM
smart_curmonth_downs_raw
INNER JOIN ldap_karen ON smart_curmonth_downs_raw.username = ldap_karen.uid
INNER JOIN smart_items ON smart_curmonth_downs_raw.itemtitle = smart_items.Title
我想知道如何创建联接,同时始终与表 smart_curmonth_downs_raw 中的行保持一对一关系。
例如,如果 ldap_karen 中没有 uid,我就会遇到问题。我发现的最后一个问题是我们的 CMS 允许重复的 itemtitle。因此,如果我运行查询,我会得到更多行,因为它为每个项目标题创建一行。例如,是否有一种方法可以仅捕获 smart_items 中的最后一个 itemtitle。我真的很想保持相同的行数 - 而且我无法控制其他表的完整性问题。
smart_curmonth_downs_raw 表是原始下载信息(下载统计信息),karen 表添加唯一的用户信息,smart_items 表添加唯一的项目(下载)信息。它们都很重要。如果用户进行了下载但被从 karen 表中删除,我希望看到用户信息的 NULL,并且如果 smart_items 中有多个具有相同名称的项目,那么我只想看到具有最高值的项目身份证号。
最佳答案
听起来 smart_curmonth_downs_raw
和 ldap_karen
之间的关系是可选的,这意味着您要使用 LEFT JOIN
来连接第一个表,如果右表不存在,则使用NULL作为右表的列值。
就 smart_items 表中的最后一项而言,您可以使用此查询。
SELECT title, MAX(id) AS max_id
FROM smart_items
GROUP BY title;
将该查询与其他逻辑结合起来,尝试将此查询作为解决方案。
SELECT COALESCE(ldap_karen.uid, 'Unknown') AS uid,
COALESCE(ldap_karen.supemail, 'Unknown') AS supemail,
COALESCE(ldap_karen.regionname, 'Unknown') AS regionname,
smart_curmonth_downs_raw.username,
smart_curmonth_downs_raw.email,
smart_curmonth_downs_raw.publisher,
smart_curmonth_downs_raw.itemtitle,
smart_items.`Owner`
FROM smart_curmonth_downs_raw
INNER JOIN (SELECT title, MAX(id) AS max_id
FROM smart_items
GROUP BY title) AS most_recent
ON smart_curmonth_downs_raw.itemtitle = most_recent.Title;
INNER JOIN smart_items
ON most_recent.max_id = smart_items.id
LEFT JOIN ldap_karen
ON smart_curmonth_downs_raw.username = ldap_karen.uid;
关于mysql - mysql中坏数据如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22873084/