【发布时间】:2015-07-18 09:40:44
【问题描述】:
不知道有没有被问过类似的问题,但是我在stackoverflow的mysql上看了一个多小时
我的问题是,我有多个表,我需要在 mysql 中使用左连接和内连接来加入它们
实体表:
id (key) | entityName
1 | john
2 | harris
3 | henry
4 | mark
5 | dom
活动表
id (key) | entityID | status
1 | 1 | 1
2 | 2 | 0
3 | 4 | 1
地理数据表
id (key) | entityID | moment (timestamps when the entry was done)
1 | 1 | 1429542320 (smaller)
2 | 1 | 1429542331 (bigger)
3 | 2 | 1429542320 (smaller)
4 | 2 | 1429542331 (biger)
5 | 4 | 1429542331 (bigger)
信息表
id (key) | entityID | infos | date
1 | 1 | xxx | today
2 | 1 | xxx | yesterday
3 | 2 | xxx | today
4 | 2 | xxx | yesterday
5 | 3 | xxx | yesterday
6 | 5 | xxx | today
7 | 5 | xxx | yesterday
8 | 5 | xxx | tomorrow
所以基本上,我需要每个拥有今天信息的实体 此外,如果他们的状态为真(或 1)(来自活动表),请在地理数据表中显示他们的日期。
所以这就是我所拥有的:
SELECT e.id,
e.entityName,
i.infos,
a.status,
MAX(g.moment) -- but the max only if status =1
FROM entities AS e
LEFT JOIN activity AS a ON a.entityID = e.id
LEFT JOIN geodata AS g ON g.entityID = e.id
INNER JOIN infos AS i ON e.id = i.entityID
WHERE i.date = 'today'
GROUP BY e.id
我希望每个实体都有关于今天的信息,但其中一些也有活动,所以我想显示它(如果它不只是让左连接放 NULL)如果状态为 0,我不'不需要那一刻,但如果它是真的,我只需要更大的一个(它的数字,所以 Max() 应该这样做但它会中断)
预期结果是:
id (key) | entityName | infos | status | MAX(moment) | ..other columns
1 | john | xxx | 1 | 1429542331 (the bigger one)
2 | harris | xxx | 0 | NULL
5 | dom | xxx | NULL | NULL
如果有人可以帮助我,我将非常感激 :) PS:对不起,我的英语不是我的母语
【问题讨论】:
标签: mysql sql join left-join inner-join