MS Access检查下一个相关记录,以便在表单中弹出一个指示器?

时间:2014-02-10 17:26:27

标签: mysql vba ms-access

我有一个连接到MySQL数据库的MS Access表单。此表单包含人口统计和实验室数据。实验室数据是多边的1:n关系。

以下是示例实验室数据:

Lab_tbl

ID (pk) Animal_ID (fk) Fruit ....... Date

100 ................ 1 .................. {{1 }} ..... Banana

1/1/13 ................ 101 .................. {{1 }} ....... 1

Apple ................ 2/6/12 ................. {{1} } ..... 102

2 ............... Banana ................. 2/4/13 ....... 103

1 ............... Apple ................. 1/13/14 104

3 ............... Pineapple ................. 3/1/12 ..... 105

我希望表单告诉用户动物已经改变了它在桌子上吃的食物类型。我对vba有一些了解,主要是展示,所以改变形式不是问题。我完成的前几个步骤是运行2 Animal_ID并按Fruit ASC排序。我不能依赖于要求数据库检查ID + 1,因为添加记录的顺序不会连续到其Animal_ID。我想我需要先Banana。我需要帮助来表明动物吃了不同类型的水果。

1 个答案:

答案 0 :(得分:0)

以下SQL Fiddle演示了以下查询,该查询应该为您提供最新的水果以及之前为特定Animal_ID吃的水果:

SELECT mt.Animal_ID, mt.id, Fruit AS NewestFruitEaten,
  (
    SELECT st.Fruit
    FROM Lab_tbl AS st
    WHERE st.ID < mt.ID AND st.Animal_ID = 1
    ORDER BY st.ID DESC
    LIMIT 1
  ) AS OldFruitEaten
FROM Lab_tbl AS mt
WHERE mt.Animal_ID = 1
ORDER BY mt.ID DESC
LIMIT 1

如果您想要一份包含最新水果和以前吃水果的所有Animal_ID的完整清单,那么以下内容应该有效(SQL Fiddle):

SELECT DISTINCT did.Animal_ID,
(
  SELECT mt.Fruit
  FROM Lab_tbl AS mt
  WHERE mt.Animal_ID = did.Animal_ID
  ORDER BY mt.ID DESC
  LIMIT 1
) AS NewestFruitEaten,
(
  SELECT st.Fruit
  FROM Lab_tbl AS st
  WHERE st.ID < 
  (
    SELECT sst.ID 
    FROM Lab_tbl AS sst
    WHERE sst.Animal_ID = did.Animal_ID
    ORDER BY sst.ID DESC
    LIMIT 1
  )
  AND st.Animal_ID = did.Animal_ID
  ORDER BY st.ID DESC
  LIMIT 1
) AS OlderFruitEaten
FROM Lab_tbl AS did

编辑 ,要获取吃多个水果的动物列表,请使用以下查询(SQL Fiddle):

SELECT DISTINCT t1.Animal_ID 
FROM Lab_tbl t1
INNER JOIN Lab_tbl t2 ON t1.Animal_ID = t2.Animal_ID
  AND t1.Fruit <> t2.Fruit