MySQL查询 - 选择最新配置和最近的操作

时间:2012-07-24 16:55:33

标签: mysql sql

我真的需要帮助解决这个问题。

我有四张桌子:

[Assets]
[id | serial_number | date_created] (other stuff)

[Parts]
[id | unit_number | date_created] (other stuff)

[Groups]
[id | asset_id | part_id | date_created] (other stuff)

[Activity]
[id | group_id | date_recorded | action_id] (other stuff)

如何选择所有资源并查找最近的配对(组)以及该组中的最新活动。在一个记录行中。

编辑:我曾尝试过:

  1. 我是用php做的,但它非常难看,需要三个单独的查询。

  2. 我通过单独的SELECT从每个表中选择了所有属性,我认为这是一种可怕的方式

    SELECT
        *,
        (
            SELECT
                part_id
            FROM
                groups
            ORDER BY
                date_created 
            DESC
            LIMIT 1
        ) AS part_id
    FROM
        assets
    
  3. 要抓住part_id我做一个嵌套选择,但如果我需要9个属性,我需要9个嵌套选择,这是一个坏方法?

1 个答案:

答案 0 :(得分:0)

您的查询建议如下:

SELECT *
FROM assets a cross join
     (select *
      from groups
      order by date_created
      limit 1
     ) g

但是,我怀疑您可能真的想在某个字段(组ID?部分ID?)上加入资产和组,并根据该字段选择最新记录。以下查询执行此操作,假设parts是匹配字段:

SELECT *
FROM assets a join
     (select *
      from groups g join
           (select g.part_id, max(date_created) as maxdate
            from groups g
            group by g.part-id
           ) gmax
           on g.part_id = gmax.part_id and
              g.date_created = gmax.maxdate
     ) g
     on a.parts_id = g.parts_id