Cross join ignores where clause
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 buil开发者_如何学Cding_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.
Try this way:
SELECT
s.shop_person, sum(b.banana_amount) as Amt, , sum(shop_time) as TimeAmt
FROM bananas b
INNER JOIN buildings bu ON b.banana_building = bu.building_id
INNER JOIN shopping s ON bu.building_id = s.shop_building
WHERE
bu.building_city = N'London'
GROUP BY s.shop_person
This query is different, but it does what you want - 'the amount of bananas each person has bought in London'
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.
SELECT tt.shop_person,
tt.shop_building,
SUM(tt.shop_time) AS shoptime,
ISNULL(SUM(tz.banana_amount), 0) AS bananas
FROM dbo.shopping tt
INNER JOIN dbo.buildings tu ON tt.shop_building = tu.building_id
LEFT OUTER JOIN
(SELECT banana_person, banana_building, SUM(banana_amount) AS banana_amount
FROM bananas
GROUP BY banana_person, banana_building) tz
ON tt.shop_person = tz.banana_person AND tt.shop_building = tz.banana_building
WHERE (tu.building_city = 'London')
GROUP BY tt.shop_person, tt.shop_building
I had to add an aggregate function around tz.banana_amount
- which one (SUM, MIN, MAX) doesn't matter.
Result:
shop_person shop_building shoptime bananas
Brian 1 40 0
Tom 1 20 1
Brian 3 30 1
I played around with different amounts in bananas
etc. and it works correctly.
精彩评论