从不同的表中选择值和计数

时间:2019-04-16 14:45:07

标签: mysql

我有2个表,其中一个表存储了带有引荐ID的用户信息。 另一个表收集记录并应用我从中获得该表格的引荐ID。

我已经进行了2个查询,我想加入一个查询。

ID = 205391的示例查询

---- Select email from refer 205391
SELECT email FROM mautic_leads WHERE refer_id IN 
(SELECT refer_id FROM mautic_form_results_64_form_db_te WHERE refer_id = "205391")
---- Count results of refer 205391
(SELECT COUNT(*) AS `count` FROM `mautic_form_results_64_form_db_te` where ref = 205391)

我正在寻找结果为

Email |  Count Ref
---------------
test@test.com     5

表结构:

CREATE TABLE `mautic_form_results_64_form_db_te` (
  `submission_id` int(11) NOT NULL,
  `form_id` int(11) NOT NULL,
  `nombre` longtext COLLATE utf8_unicode_ci,
  `apellido` longtext COLLATE utf8_unicode_ci,
  `correo_electronico` longtext COLLATE utf8_unicode_ci,
  `ref` longtext COLLATE utf8_unicode_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `mautic_form_results_64_form_db_te` (`submission_id`, `form_id`, `nombre`, `apellido`, `correo_electronico`, `ref`) VALUES
(7699, 64, 'test', 'test', 'test@test.net', '201374'),
(7700, 64, 'test2', 'test2', 'test@test.net', '205391'),
(7701, 64, 'test3', 'test3', 'test@test.net', '205391'),
(7704, 64, 'test4', 'test4', 'test@test.net', '205391'),
(7705, 64, 'test5', 'test5', 'test@test.net', '205391'),
(7706, 64, 'test6', 'test6', 'test@test.net', '201374'),
(7707, 64, 'test7', 'test7', 'test@test.net', '201374'),
(7708, 64, 'test8', ' test8 ', 'test@test.net', '205391');

CREATE TABLE `mautic_leads` (
  `email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `refer_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `referido_por_usuario` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `mautic_leads` (`email`, `refer_id`, `referido_por_usuario`) VALUES
('test1@test.com', '201374', NULL),
('test2@test.com', '205388', NULL),
('test3@test.com', '205389', NULL),
('test3@test.com', '205390', NULL),
('test2@test.com', '205391', NULL);

有帮助吗? 谢谢

3 个答案:

答案 0 :(得分:0)

怎么样?

SELECT (SELECT email 
    FROM   mautic_leads 
    WHERE  refer_id IN (SELECT refer_id 
                        FROM   mautic_form_results_64_form_db_te 
                        WHERE  refer_id = "205391")) as email, 
   Count(*) AS `count` 
FROM   `mautic_form_results_64_form_db_te` 
WHERE  ref = 205391 

答案 1 :(得分:0)

现在,我看到了您的表结构,请使用:

SELECT b.email,COUNT(a.submission_id) as `count`
FROM mautic_form_results_64_form_db_te a
JOIN mautic_leads b on  b.refer_id = a.ref
WHERE ref = 205391

答案 2 :(得分:0)

您可以尝试以下查询:

SELECT mautic_leads.email as email, (SELECT count(*) as count from \
mautic_form_results_64_form_db_te where ref = "205391") as count \
from mautic_leads where refer_id = "205391";

您将得到如下结果:

+----------------+-------+
| email          | count |
+----------------+-------+
| test2@test.com |     5 |
+----------------+-------+