2015-10-20 42 views
0

加入我想在mysql中加入一个查询的输出与第二个表:与内部问题在MySQL

(select 
    A.name, A.address, sum(C.penalty_points) as points 
from 
    restaurant as A 
     inner join 
    inspection as B ON A.restaurant_id = B.restaurant_id 
     inner join 
    violation as C ON C.violation_id = B.violation_id 
group by A.name) 

输出:

name    address         points 
Kitchen 305  660 Washington Ave       2 
PL8 Kitchen  Southeast 17th Street in Fort Lauderdale 11 
Prime One Twelve 112 Ocean Drive       5 
Seasons 52   Palm Beach Gardens       3 
Six Tables   32 East Atlantic       8 
Table 26   Park Racks Downtown Eatery     2 

第二个表的结果:

select * from health_points 

输出:

points health_grade 
0  A 
1  A 
2  A 
3  A 
4  A 
5  B 
6  B 
7  B 
8  B 
9  B 
10  B 
11  C 
12  C 
13  C 
14  C 
15  C 
17  FAIL 
18  FAIL 
19  FAIL 

有没有一种方法可以将第一个查询与第二个表相结合并提取健康等级?我正在尝试这样的:

(select 
    A.name, A.address, sum(C.penalty_points) as points 
from 
    restaurant as A 
     inner join 
    inspection as B ON A.restaurant_id = B.restaurant_id 
     inner join 
    violation as C ON C.violation_id = B.violation_id 
group by A.name) as D inner join health_points as E on D.points = E.points 

但它显示错误在MySQL?任何指向哪里我会错在这里?

+0

@Thorsten你是如何删除所有的演员逗号这么容易?并放置列? – python

+1

我已经使用过一个文本编辑器:-) –

+0

@我可以给你一个大拇指:)或积分 – python

回答

2

你缺少外SELECT条款:

SELECT D.*, E.health_grade 
FROM (
    SELECT A.name, A.address, sum(C.penalty_points) as points 
    FROM restaurant A 
    JOIN inspection B ON (A.restaurant_id = B.restaurant_id) 
    JOIN violation C ON (C.violation_id = B.violation_id) 
    GROUP BY A.name 
) D 
JOIN health_points E ON (D.points = E.points) 
+0

Man!每个数据库都是如此不同:/。主席先生,非常感谢你 – python

+0

我只是缺少外部选择状态,否则一切都很好。 – python

+0

谢谢:)我删除了“不适合”的说明。 –

2

你可以这样做:

SELECT 
    e.health_grade, 
    d.points 
FROM 
(
    select 
    A.name, A.address, sum(C.penalty_points) as points 
    from restaurant as A 
    inner join inspection as B ON A.restaurant_id = B.restaurant_id 
    inner join violation as C ON C.violation_id = B.violation_id 
    group by A.name, A.address 
) as D 
inner join health_points as E on D.points = E.points 
+0

谢谢你的评论,但不能接受这两个答案。竖起大拇指:) – python

+0

@RakeshRanjanSukla - 不客气,你应该接受另一个答案,因为他速度更快。 –

+0

我只能在6分钟后才能接受堆栈溢出的事情 – python