我有两个表t1
和t2
,并希望得到输出t1,其中添加了一列,给出了t2中存在(id,category)的行数。
以下是小数据集的示例:
CREATE TABLE IF NOT EXISTS `t1` (
`key` int(11) NOT NULL,
`id` int(11) NOT NULL,
`category` int(11) NOT NULL,
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `t1` (`key`, `id`, `category`) VALUES
(1, 12, 101),
(2, 12, 104),
(3, 13, 102),
(4, 14, 101),
(5, 15, 102);
CREATE TABLE IF NOT EXISTS `t2` (
`key` int(11) NOT NULL,
`id` int(11) NOT NULL,
`category` int(11) NOT NULL,
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `t2` (`key`, `id`, `category`) VALUES
(1, 12, 101),
(2, 12, 102),
(3, 13, 101),
(4, 13, 104),
(5, 12, 101),
(6, 15, 102);
以下是输出我希望,最后一列是所需的信息:
t1 updated
key, id, category, count_t2_id_category
1, 12, 101, 2 # because (12,101) appears 2 times in t2
2, 12, 104, 0 # because (12,104) appears 0 times in t2
3, 13, 102, 0 # etc
4, 14, 101, 0
5, 15, 102, 1
我尝试了以下命令开始,但它错过了输出中的一些t1行:
SELECT *
FROM t1
LEFT OUTER JOIN t2 ON t1.id=t2.id AND t1.category = t2.category
GROUP BY t1.id
输出缺少t1键#2:
key id category key id category
1 12 101 1 12 101
3 13 102 NULL NULL NULL
4 14 101 NULL NULL NULL
5 15 102 6 15 102
答案 0 :(得分:1)
由于您希望不匹配行的值为零,因此它适用于LEFT JOIN
,例如:
SELECT
t1.*,
IF(t2.`key` IS NULL, 0, COUNT(t1.`key`)) AS t2_row_count
FROM
t1
LEFT JOIN t2
ON t1.id=t2.id
AND
t1.category=t2.category
GROUP BY
t1.`key`
我们正在计算t1.key
,因为对于匹配的行,它们在第一个表中是相同的(而不是第二个) - 因此,我们应该按它分组 - 而不是按字段分组在第二个表中。
提示:避免使用mysql保留字命名表/列。如果您不小心忘记反引号,这将为您节省大量时间。
答案 1 :(得分:0)
首先请将您的列名密钥更改为recid coz密钥是mysql的保留字
SELECT t1.recid,t1.id,t1.category,count(t2.category)as count FROM t1 LEFT JOIN t2 ON t1.id = t2.id AND t1.category = t2.category GROUP BY t1.id ,t1.category