使用多个表计算不同值的出现次数

时间:2014-11-18 20:52:51

标签: php mysql sql union

我在数据库中有3个表具有相似的值和相同的表结构。我试图通过唯一value获取每个user的出现次数。

数据库结构
View on SQLFiddle

TABLE_1

user | value | id 

TABLE_2

user | value | id 

TABLE_3

user | value | id 

我可以运行以下MySQL命令一次在1个表上检索所需的结果。

SELECT value,COUNT(*) as count FROM TABLE_1 GROUP BY value ORDER BY count DESC;

我需要一次在三个表中运行此命令,以便检索" value"的唯一出现次数。在"用户列表中#34;包含许多重复项。

3 个答案:

答案 0 :(得分:3)

鉴于您的意见,由于您要删除重复项,请使用UNION将表中的数据合并在一起:

SELECT value, COUNT(*) as count 
FROM (
  SELECT user, value, id
  FROM TABLE_1
  UNION
  SELECT user, value, id
  FROM TABLE_2
  UNION
  SELECT user, value, id
  FROM TABLE_3 ) t
GROUP BY value 
ORDER BY count DESC;

答案 1 :(得分:1)

您需要使用UNION -

SELECT value, COUNT(*) as count 
FROM (
    SELECT user, value, id
    FROM TABLE_1
    UNION
    SELECT user, value, id
    FROM TABLE_2
    UNION
    SELECT user, value, id
    FROM TABLE_3 ) tables
GROUP BY value 
ORDER BY count DESC;

输出 -

+-------+-----+
|car    |8    |
|boat   |4    |
|truck  |3    |
|house  |2    |
|skates |1    |
|bike   |1    |
+-------+-----+

答案 2 :(得分:1)

继续评论这是我建议你做的。

设置:

CREATE TABLE members (
    id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    username varchar(255),
);

INSERT INTO members (username)
SELECT DISTINCT user FROM table1
UNION SELECT DISTINCT user FROM table2
UNION SELECT DISTINCT user FROM table3;

改变:

ALTER table1
    ADD COLUMN user_id INT(10)
    ADD INDEX `user_id` (`user_id`);

ALTER table2
    ADD COLUMN user_id INT(10)
    ADD INDEX `user_id` (`user_id`);

ALTER table3
    ADD COLUMN user_id INT(10)
    ADD INDEX `user_id` (`user_id`);

更新

UPDATE table1 t,
JOIN members m ON m.username = t.username
    SET t.user_id = m.id;

UPDATE table2 t,
JOIN members m ON m.username = t.username
    SET t.user_id = m.id;

UPDATE table3 t,
JOIN members m ON m.username = t.username
    SET t.user_id = m.id;

删除非标准化数据

ALTER table1
    DROP user;

ALTER table2
    DROP user;

ALTER table3
    DROP user;

现在您还可以根据需要在user_id和id列上设置外键约束。

但要查询总计数,您只需加入表格。确保在每个id字段上添加索引,以便正确加入。

SELECT your_stuff
FROM members m
LEFT JOIN table1 t1 ON t1.user_id = m.id
LEFT JOIN table2 t2 ON t2.user_id = m.id
LEFT JOIN table3 t3 ON t3.user_id = m.id