mysql两张表如何关联查询?

table1和table2的某个字段相同如何进行关联查询?
问题:table1分类count如下,如何关联table2的单价并实现total_pass的值乘以单价算总价?

select product,type,
count(case when status='pass' then id end) total_pass,
count(sn) total_sn,
concat(round(count(case when status='pass' then id end)/count(sn)*100,2),'%') rate
from table1 group by product,type
效果:
product    total_pass    total_sn    rate    总价
产品1    3    5    60.00%    ¥30.00 
产品2    4    4    100.00%    ¥104.00 

table1结构:

CREATE TABLE table1(
  id INT PRIMARY KEY AUTO_INCREMENT COMMENT 'id',
  sn VARCHAR(200) COMMENT '产品序号',
  product VARCHAR(200) COMMENT '产品名称',
  type VARCHAR(200) COMMENT '产品类别',
  status VARCHAR(200) COMMENT '产品状态pass or ng'
) COMMENT='产品信息'

id    sn    product    type    status
1    AAAA    产品1    type1    pass
2    BBBB    产品1    type1    pass
3    CCCC    产品1    type1    pass
4    DDDD    产品1    type1    ng
5    EEEE    产品1    type1    ng
6    FFFF    产品2    type2    pass
7    GGGG    产品2    type2    pass
8    HHHHH    产品2    type2    pass
9    JJJJJJ    产品2    type2    pass

table2结构:

CREATE TABLE table2(
  id INT PRIMARY KEY AUTO_INCREMENT COMMENT 'id',
  type VARCHAR(200) COMMENT '产品类别',
  price VARCHAR(200) COMMENT '单价',
) COMMENT='产品价格总表'
id    type    price
1    type1    ¥10.00 
2    type2    ¥26.00 
3    type3    ¥45.00 
4    type4    ¥23.00 
5    type5    ¥14.00 

你这两个表的关联字段是什么?id?如果是id的话,直接关联不就好了?而且也没说两个表是否完全匹配,我先假定是完全匹配的

select a.id,a.product,a.type,
count(case when a.status='pass' then a.id end) total_pass,
count(case when a.status='pass' then a.id end) * max(price) 总价,
count(a.sn) total_sn,
concat(round(count(case when a.status='pass' then a.id end)/count(a.sn)*100,2),'%') rate
from table1 a,table2 b where a.id=b.id group by a.id,a.product,a.type

你这个应该不是原表结构,没人会这么设计表格的,上面的sql仅针对你这个奇怪的表结构而写


是否存在table1有的type,在table2中不存在?如果全部都存在,那么直接用type关联就好了,

select a.id,a.product,a.type,
count(case when a.status='pass' then a.id end) total_pass,
count(case when a.status='pass' then a.id end) * max(price) 总价,
count(a.sn) total_sn,
concat(round(count(case when a.status='pass' then a.id end)/count(a.sn)*100,2),'%') rate
from table1 a,table2 b where a.type=b.type group by a.id,a.product,a.type

但奇怪的是,为啥你的price是个VARCHAR?而且还带符号?,这样的话要先把符号去掉才能计算

replace(price,'¥','') 

id是自增的 所以肯定不会是id进行关联

用type进行关联

a表 join b表 就会变成另外一个 表c

可以在c表里面进行计算。