1

我有两个表,表示按日期排序的两个活动中的用户数:

表 A:在活动 1 中有日期和用户数量
表 B:在活动 2 中有数据和用户数量

问题:如何在 MYSQL 中将它们连接在一起(特别是我使用 PHPMYADMIN 进行数据操作)?我对这段代码的问题是会丢失一些条目(其中没有关于某一列中特定日期的信息):

SELECT a1.day, a1.count, b1.count
FROM table_A a1 
JOIN table_B b1 on a1.day = b1.day
ORDER BY a1.day  
4

4 回答 4

0
SELECT *
FROM table_A

UNION ALL

SELECT *
FROM table_B

会做你想做的事,但如果这是一个常规的事情,你最好简单地将两个表组合成一个表。

于 2012-08-04T00:56:36.173 回答
0
SELECT 
    u.day, SUM(count_A) AS count_A, SUM(count_B) AS count_B
FROM
(SELECT day, count AS count_A, 0 AS count_B
FROM table_A
UNION ALL
SELECT day, 0, count 
FROM table_B) AS u
GROUP BY u.day
ORDER BY u.day
于 2012-08-04T01:19:03.323 回答
0

我认为您正在寻找的是FULL OUTER JOIN您的两个表中的一个,可以像这样在 MySQL 中模拟:

SELECT   *
FROM     (
         SELECT     a.day, a.count, b.count
         FROM       table_A a
         LEFT JOIN  table_B b ON a.day = b.day

         UNION ALL

         SELECT     a.day, a.count, b.count
         FROM       table_A a
         RIGHT JOIN table_B b ON a.day = b.day
         WHERE      a.day IS NULL
         ) a
ORDER BY a.day
于 2012-08-04T01:22:50.950 回答
0

如果我理解正确,您正在尝试合并两个表并添加按“天”分组的“计数”字段的值(可能是“用户”)。

有几种方法可以完成我认为您正在尝试做的事情。在此方法中,我们将创建一个表并使用 UNION ALL、SUM 和 GROUP BY 插入 Table_A 和 Table_B 的值。

create table `Table_C` (
   `id` int unsigned primary key auto_increment,
   `day` varchar(16),
   `count` integer
);

INSERT INTO `Table_C`
SELECT * FROM ( 
    SELECT
         0 AS `id`,
        `day`,
        SUM(`count`)
    FROM ( 
       SELECT `a`.`day` AS `day`, `a`.`count` AS `count` FROM `Table_A` `a` 
         UNION ALL
       SELECT `b`.`day` AS `day`, `b`.`count` AS `count` FROM `Table_B` `b`
         ) AS `u` 
    GROUP BY `u`.`day`
    ORDER BY `u`.`day`
) AS `t1`;

但是,这里不考虑活动的“用户”。

于 2012-08-04T21:56:32.157 回答