这是一个查询示例:
SELECT ITEM.ID
, DAT1.DATE
, DAT2.DATE
, DAT3.DATE
FROM ITEM
LEFT JOIN DATES AS DAT1 ON DAT1.ITEM_ID = ITEM.ID
LEFT JOIN DATES AS DAT2 ON DAT2.ITEM_ID = ITEM.ID
LEFT JOIN DATES AS DAT3 ON DAT3.ITEM_ID = ITEM.ID
WHERE ITEM.ID > 2000
AND DAT1.FUNCTCODE ='START'
AND DAT2.FUNCTCODE ='END'
AND DAT3.FUNCTCODE ='REFURBISHED'
是否可以始终获得ID高于2000 AND的ITEMS 使用'功能代码显示日期'(1,2或3个字段)如果功能代码不存在行,则显示NULL?
由于
答案 0 :(得分:4)
将where
条件除第一个表格外的所有条件移至on
条款:
SELECT ITEM.ID, DAT1.DATE, DAT2.DATE, DAT3.DATE
FROM ITEM
LEFT JOIN DATES AS DAT1 ON DAT1.ITEM_ID = ITEM.ID AND DAT1.FUNCTCODE ='START'
LEFT JOIN DATES AS DAT2 ON DAT2.ITEM_ID = ITEM.ID AND DAT2.FUNCTCODE ='END'
LEFT JOIN DATES AS DAT3 ON DAT3.ITEM_ID = ITEM.ID AND DAT3.FUNCTCODE ='REFURBISHED'
WHERE ITEM.ID > 2000;
答案 1 :(得分:1)
如果要查看id超过2000的每个项目,无论它是否具有所有相关日期记录,请将最后三个项目放在条件中。
SELECT ITEM.ID,DAT1.DATE,DAT2.DATE,DAT3.DATE
FROM ITEM
LEFT JOIN DATES AS DAT1 ON DAT1.ITEM_ID = ITEM.ID
LEFT JOIN DATES AS DAT2 ON DAT2.ITEM_ID = ITEM.ID
LEFT JOIN DATES AS DAT3 ON DAT3.ITEM_ID = ITEM.ID
WHERE ITEM.ID > 2000
这将为您提供如下结果:
ID DATE DATE DATE
2001 null null null (item with no corresponding date records)
2002 <date> <date> <date> (item with all three date records)
2003 <date> null null (item with only the first date record)