我在数据库中有3个表具有相似的值和相同的表结构。我试图通过唯一value
获取每个user
的出现次数。
数据库结构
View on SQLFiddle
user | value | id
user | value | id
user | value | id
我可以运行以下MySQL命令一次在1个表上检索所需的结果。
SELECT value,COUNT(*) as count FROM TABLE_1 GROUP BY value ORDER BY count DESC;
我需要一次在三个表中运行此命令,以便检索" value"的唯一出现次数。在"用户列表中#34;包含许多重复项。
答案 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