交叉连接忽略where子句
表:购物
shop_id shop_building shop_person shop_time
1 1 Brian 40
2 2 Brian 31
3 1 Tom 20
4 3 Brian 30
表:建筑物
building_id building_city
1 London
2 Newcastle
3 London
4 London
表:香蕉
banana_id banana_building banana_amount banana_person
1 2 1 Brian
2 3 1 Brian
2 1 1 Tom
我现在希望它显示每个人在伦敦购买的香蕉数量。
我使用了这段代码:
SELECT tt.*, tu.*, tz.*,
SUM(shop_time) AS shoptime,
Ifnull(banana_amount, 0) AS bananas
INNER JOIN buildings tu ON tt.shop_building=tu.building_id
FROM shopping tt
LEFT OUTER JOIN (SELECT banana_person, banana_building,
SUM(banana_amount) AS banana_amount
FROM bananas
GROUP BY banana_person) tz
ON tt.shop_person = tz.banana_person AND tt.shop_building = tz.banana_building
WHERE tu.building_city = 'London'
GROUP BY shop_person;
但它不起作用。就好像我告诉它为时已晚,它应该只在伦敦寻找,因为它忽略了这一点。
Table: Shopping
shop_id shop_building shop_person shop_time
1 1 Brian 40
2 2 Brian 31
3 1 Tom 20
4 3 Brian 30
Table: buildings
building_id building_city
1 London
2 Newcastle
3 London
4 London
Table:bananas
banana_id banana_building banana_amount banana_person
1 2 1 Brian
2 3 1 Brian
2 1 1 Tom
I now want it show me the amount of bananas each person has bought in London.
I used this code:
SELECT tt.*, tu.*, tz.*,
SUM(shop_time) AS shoptime,
Ifnull(banana_amount, 0) AS bananas
INNER JOIN buildings tu ON tt.shop_building=tu.building_id
FROM shopping tt
LEFT OUTER JOIN (SELECT banana_person, banana_building,
SUM(banana_amount) AS banana_amount
FROM bananas
GROUP BY banana_person) tz
ON tt.shop_person = tz.banana_person AND tt.shop_building = tz.banana_building
WHERE tu.building_city = 'London'
GROUP BY shop_person;
But it doesn't work. It's as if I'm telling it too late, that it should only look in London, as it ignores this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这种方式:
这个查询是不同的,但它满足您的要求 - “每个人在伦敦购买的香蕉数量”
Try this way:
This query is different, but it does what you want - 'the amount of bananas each person has bought in London'
在不知道您正在使用什么数据库的情况下,这里是 mssql 的工作版本。
我实际上重建了表格以确保它是正确的。
对于其他数据库系统,您可能必须在 SELECT 语句中使用除
ISNULL
之外的其他函数。我必须在 tz.banana_amount 周围添加一个聚合函数 - 哪一个(SUM、MIN、MAX)并不重要。
结果:
我在
香蕉
等中尝试了不同的数量,并且它工作正常。Without knowing what database you are using, here is a working version for mssql.
I actually rebuilt the tables to make sure it is correct.
For other database systems you'll probably have to use an other function than
ISNULL
in the SELECT statement.I had to add an aggregate function around
tz.banana_amount
- which one (SUM, MIN, MAX) doesn't matter.Result:
I played around with different amounts in
bananas
etc. and it works correctly.