Php,MySql加入3个表并计算总数

时间:2016-06-15 21:49:23

标签: php mysql join

我有3个连接表,并尝试从中提取记录,但由于某种原因无法实现它。我在这里创建了SQL Fiddle:http://sqlfiddle.com/#!9/9eeaf/1/0

我现在得到的只是COUNT为1>的记录。显示,但我需要显示所有这些,无论计数是0

CREATE TABLE `questions` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `question` varchar(150) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `questions` (`id`, `question`) VALUES
(1, 'How do you find our site?'),
(2, 'What is your favoutite color');



CREATE TABLE `options` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `question_id` int(11) NOT NULL,
  `value` varchar(250) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


INSERT INTO `options` (`id`, `question_id`, `value`) VALUES
(1, 1, 'Hard'),
(2, 1, 'Easy'),
(3, 1, 'Very Easy'),
(4, 1, 'Piece of cake'),
(5, 1, 'Green'),
(6, 1, 'Blue'),
(7, 1, 'Red'),
(8, 1, 'Black');


CREATE TABLE `votes` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `option_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_option` (`option_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `votes` (`id`, `option_id`) VALUES
(1, 1),
(2, 1),
(3, 2),
(4, 4),
(5, 5);

SELECT 
  q.question,
  o.value,
  IFNULL(COUNT(DISTINCT v.option_id), 0) AS total 
FROM
  questions AS q 
  LEFT JOIN OPTIONS AS o 
    ON o.question_id = q.id 
  LEFT JOIN votes AS v 
    ON v.option_id = o.id 
GROUP BY v.option_id;

1 个答案:

答案 0 :(得分:0)

我认为你在寻找这个:

SELECT
  q.question,
  o.value,
  IFNULL(COUNT(v.option_id), 0) AS total 
FROM
  options AS o
  LEFT JOIN votes AS v 
    ON o.id = v.option_id
  JOIN questions as q
  ON o.question_id = q.id
 GROUP BY o.id;

小提琴:http://sqlfiddle.com/#!9/9eeaf/26