Mariadb

GROUP BY 不適用於空字元串

  • March 22, 2022

我想分組email。有時email會在記錄中失去,因此不應對其進行分組。

分組時如何為空字元串創建例外?

CREATE TABLE example (
 id INT NOT NULL AUTO_INCREMENT,
 fullname VARCHAR(100) NOT NULL,
 email VARCHAR(100) NOT NULL,
 something VARCHAR(255) NOT NULL
);
INSERT INTO example (id, fullname, email, something) VALUES
 (1, 'Name 1', 'name1@example.com', 'Something 1'),
 (2, 'Name 2', '', 'Something 2'),
 (3, 'Name 1', 'name1@example.com', 'Something 3'),
 (4, 'Name 3', 'name3@example.com', 'Something 4'),
 (5, 'Name 3', 'name3@example.com', 'Something 5'),
 (6, 'Name 4', '', 'Something 6');

結果,我想:

SELECT fullname, email FROM example GROUP BY email [...];
+----------+-------------------+
| fullname | email             |
+----------+-------------------+
| Name 2   |                   |
| Name 4   |                   |
| Name 1   | name1@example.com |
| Name 3   | name3@example.com |
+----------+-------------------+

您可以使用 UNION 並使用它來獲得想要的結果。

如果列沒有 ’’ 作為文本,您可以使用 WHERE email IS NULL 而不是 WHERE email = ''

CREATE TABLE example (
  id INT NOT NULL AUTO_INCREMENT Primary KEY,
  fullname VARCHAR(100) NOT NULL,
  email VARCHAR(100) NOT NULL,
  something VARCHAR(255) NOT NULL
);
INSERT INTO example (id, fullname, email, something) VALUES
  (1, 'Name 1', 'name1@example.com', 'Something 1'),
  (2, 'Name 2', '', 'Something 2'),
  (3, 'Name 1', 'name1@example.com', 'Something 3'),
  (4, 'Name 3', 'name3@example.com', 'Something 4'),
  (5, 'Name 3', 'name3@example.com', 'Something 5'),
  (6, 'Name 4', '', 'Something 6');
SELECT GROUP_CONCAT(DISTINCT fullname), email 
FROM example 
WHERE email <> ''
GROUP BY email 
UNION
SELECT fullname, email 
FROM example 
WHERE email = ''
ORDER BY email;
GROUP_CONCAT(DISTINCT 全名) | 電子郵件 
:------------------------------ | :----------------
Name 2 | 
Name 4 | 
Name 1 | name1@example.com
Name 3 | name3@example.com
SELECT GROUP_CONCAT(DISTINCT fullname), email 
FROM example 
GROUP BY email 
GROUP_CONCAT(DISTINCT 全名) | 電子郵件 
:------------------------------ | :----------------
姓名 2,姓名 4 | 
Name 1 | name1@example.com
Name 3 | name3@example.com

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/270843