简体   繁体   中英

unique records in mysql one-to-many join without DISTINCT or GROUP BY

Here's the basic query:

SELECT
    some_columns
FROM
    d
JOIN
    m ON d.id = m.d_id
JOIN
    s ON s.id = m.s_id
JOIN
    p ON p.id = s.p_id
WHERE
    some_criteria   
ORDER BY
    d.date DESC
LIMIT 25

Table m can contain multiple s_id s per each d_id . Here's a super simple example:

+--------+--------+------+
| id     | d_id   | s_id |
+--------+--------+------+
| 317354 | 291220 |  642 |
| 317355 | 291220 |   32 |
+--------+--------+------+
2 rows in set (0.00 sec)

Which we want. But, obviously, it's producing duplicate d records in this particular query.

These tables have lots of columns, and I need to edit these down due to the sensitive nature of the data, but here's the basic structure as it pertains to this query:

| d  | CREATE TABLE `d` (
  `id` bigint(22) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),
  KEY `date` (`date`)
) ENGINE=InnoDB |

| m | CREATE TABLE `m` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `d_id` bigint(20) NOT NULL,
  `s_id` bigint(20) NOT NULL,
  `is_king` binary(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `d_id` (`d_id`),
  KEY `is_king` (`is_king`),
  KEY `s_id` (`s_id`)
) ENGINE=InnoDB |

| s | CREATE TABLE `s` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `p_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `p_id` (`p_id`)
) ENGINE=InnoDB |

| p | CREATE TABLE `p` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB |

Now, previously, we had a GROUP BY d.id in place to grab uniques. The data here are now huge, so we can no longer realistically do that. SELECT DISTINCT d.id is even slower.

Any ideas? Everything I come up with creates a problem elsewhere.

Does changing "JOIN m ON d.id = m.d_id" to "LEFT JOIN m ON d.id = m.d_id" accomplish what you're looking for here?

I'm not sure I understand your goal clearly, but "table m contains many rows per each d" immediately has me wondering if you should be using some other type of join to accomplish your ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM