如何在MySQL中加入多个表?

时间:2014-03-30 11:32:15

标签: php mysql

表格关系的图像可以在image找到。

-- Table structure for table `area`
CREATE TABLE `area` (
  `area_id` int(10) NOT NULL auto_increment,
  `area_name` varchar(255) NOT NULL,
  PRIMARY KEY  (`area_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `area` (`area_id`, `area_name`) VALUES
(1, 'Area 1'),
(2, 'Area 2'),
(3, 'Area 3'),
(4, 'Area 4');

-- Table structure for table `fruits`


CREATE TABLE `fruits` (
  `fruit_id` int(10) NOT NULL auto_increment,
  `fruit_name` varchar(255) NOT NULL,
  `area_id` int(10) NOT NULL,
  PRIMARY KEY  (`fruit_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;



INSERT INTO `fruits` (`fruit_id`, `fruit_name`, `area_id`) VALUES
(1, 'Apple', 1),
(2, 'Orange', 1),
(3, 'Mango', 2),
(4, 'Apricot', 3);


-- Table structure for table `vegetables`
CREATE TABLE `vegetables` (
  `veg_id` int(10) NOT NULL auto_increment,
  `veg_name` varchar(255) NOT NULL,
  `area_id` int(10) NOT NULL,
  PRIMARY KEY  (`veg_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `vegetables` (`veg_id`, `veg_name`, `area_id`) VALUES
(1, 'Chickpea', 1),
(2, 'Drumstick', 4);

如果我使用以下查询,我得到如下输出

SELECT
    `area`.`area_name` AS AreaName
    ,COUNT(*) AS num
FROM
    `area`
    INNER JOIN `fruits`
        ON (`fruits`.`area_id` = `area`.`area_id`)
    GROUP BY `fruits`.area_id   

UNION ALL

SELECT
    `area`.`area_name` AS AreaName
    ,COUNT(*) AS num
FROM
    `area`

    INNER JOIN `vegetables`  
        ON (`vegetables` .`area_id` = `area`.`area_id`)
    GROUP BY `vegetables`.area_id

AREANAME NUM
  区域1 2
  区域2 1
  区域3 1
  区域1 1
  区域4 1

但我希望输出如下:

它应该取出蔬菜和水果中存在的所有区域,如果该区域在水果或蔬菜中重复,则应该通过总计水果和蔬菜的数量来返回area_id的总数。所以输出将是如下所示

AREANAME NUM
  区域1 3
  区域2 1
  区域3 1
  区域4 1

1 个答案:

答案 0 :(得分:1)

您可以对查询使用子选择,并使用SUM()添加相同区域的计数

SELECT t.AreaName ,SUM(t.num) num
FROM ( ....) t
GROUP BY t.AreaName

Fiddle Demo