简体   繁体   English

如何在 MySQL 中加入多个表?

[英]How to join with multiple tables in MySQL?

The image of the table relation can be found at image .表关系的图像可以在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);

If I use the following query I get the output as below如果我使用以下查询,我会得到如下输出

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 AREANAME NUM
Area 1 2区域 1 2
Area 2 1区域 2 1
Area 3 1区域 3 1
Area 1 1区域 1 1
Area 4 1区域 4 1

But I want the output to be like:但我希望输出是这样的:

it should fetch all the areas which are present in vegetables and fruits and if the area is repeating in either fruits or vegetables it should return the total count of area_id by totalling the count of fruits and vegetables.. so the output will be like below它应该获取蔬菜和水果中存在的所有区域,如果该区域在水果或蔬菜中重复,它应该通过总计水果和蔬菜的数量来返回 area_id 的总数..所以输出将如下所示

AreaName num AREANAME NUM
Area 1 3区域 1 3
Area 2 1区域 2 1
Area 3 1区域 3 1
Area 4 1区域 4 1

You can use a subselect over your query and use SUM() to add the counts for same area您可以在查询上使用子选择并使用SUM()添加相同区域的计数

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

Fiddle Demo小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM