新手:mysql将2个表连接起来并计算结果

时间:2012-06-21 18:37:03

标签: mysql sql join count

我试图加入2个表并计算结果。 我有这些表格;

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `segments`
-- ----------------------------
DROP TABLE IF EXISTS `segments`;
CREATE TABLE `segments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `substr_id` int(255) NOT NULL,
  `substr` varchar(255) NOT NULL,
  `count` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Records of `segments`
-- ----------------------------
BEGIN;
INSERT INTO `segments` VALUES ('1', '1', 'book', '2'), ('2', '2', 'ooki', '1'), ('3', '2', 'okin', '1'), ('4', '2', 'king', '1');
COMMIT;

-- ----------------------------
--  Table structure for `words`
-- ----------------------------
DROP TABLE IF EXISTS `words`;
CREATE TABLE `words` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `substr_id` int(11) NOT NULL,
  `word` varchar(255) NOT NULL,
  `cleaned` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

-- ----------------------------
--  Records of `words`
-- ----------------------------
BEGIN;
INSERT INTO `words` VALUES ('1', '1', 'book', '0'), ('2', '2', 'booking', '0'), ('3', '2', 'booking', '0'), ('4', '2', 'booking', '0');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

使用sql + data更改了问题。

我想:

 SELECT words with there count from segments.count based upon there substr_id. 

任何人都可以帮我完成这件事吗?我不擅长SQL有红色文档和一些教程,但我不知道如何在一个查询中完成上述所有操作。

3 个答案:

答案 0 :(得分:2)

 SELECT word, count
   FROM words NATURAL JOIN segments;

应该做的伎俩。我建议做一些更多的研究。 http://en.wikipedia.org/wiki/Join_(SQL

答案 1 :(得分:1)

您需要聚合函数COUNT()才能计算查询结果。

有许多链接可以帮助解决这个问题,但像http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html这样的内容应该会有所帮助。

答案 2 :(得分:1)

你可能想要某种加入条件,否则你会得到一个笛卡尔积,但这应该让你开始:

SELECT COUNT(*)
FROM words
JOIN count --add an ON condition here unless you want a cartesian product

有点不清楚你想要做什么,但随意澄清这是不是你想要的。

祝你好运!