【问题标题】:How can I achieve this double join in SQL?如何在 SQL 中实现这种双重联接?
【发布时间】:2013-02-01 07:15:19
【问题描述】:

我有这个查询,它连接了存储在缓存表中的事件的名称。

SELECT OccurrenceCache.occurrence_date, CalendarItem.summary FROM OccurrenceCache
    INNER JOIN CalendarItem ON CalendarItem.ROWID = OccurrenceCache.event_id
    WHERE OccurrenceCache.occurrence_date >= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day')) AND OccurrenceCache.occurrence_end_date <= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day') + 24 * 60 * 60);

现在我也想包含事件的位置数据,这些数据存储在一个名为 Location 的表中。位置条目由 CalendarItem.location_id 引用(0 表示未指定位置)。我尝试了另一个 JOIN 语句,但它不起作用:

SELECT OccurrenceCache.occurrence_date, CalendarItem.summary, Location.title FROM OccurrenceCache
    INNER JOIN CalendarItem ON CalendarItem.ROWID = OccurrenceCache.event_id
    INNER JOIN Location ON Location.ROWID = CalendarItem.location_id
    WHERE OccurrenceCache.occurrence_date >= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day')) AND OccurrenceCache.occurrence_end_date <= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day') + 24 * 60 * 60);

它返回 0 个结果。

【问题讨论】:

  • 很难说没有样本数据,但我猜:OccurenceCache 中的每一行在 CalendarItem 位置中是否都有匹配的条目?如果不是,请使用“LEFT JOIN”而不是“INNER JOIN”。
  • @Krumelur:是的,解决了。谢谢!

标签: sql join sqlite inner-join


【解决方案1】:

如果您在Location 表中的所有条目都与calenderitem 表不匹配,则使用LEFT JOIN 代替将是解决方案。

SELECT OccurrenceCache.occurrence_date, CalendarItem.summary, Location.title FROM OccurrenceCache
    INNER JOIN CalendarItem ON CalendarItem.ROWID = OccurrenceCache.event_id
    LEFT JOIN Location ON Location.ROWID = CalendarItem.location_id
    WHERE OccurrenceCache.occurrence_date >= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day')) AND OccurrenceCache.occurrence_end_date <= (strftime('%s', 'now', 'localtime', 'start of day') - strftime('%s', '2001-01-01', 'start of day') + 24 * 60 * 60);

Using Outer Joins in SQL

【讨论】:

    猜你喜欢
    • 2023-01-17
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2018-04-17
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多