我有两个表格,其中包含有关我在查询中加入的图形的信息。第一个表包含图纸的唯一编号,标题和绘制对象。第二个表包含修订版和图纸修订日期。
表1
|dwg_id|project_no|sws_dwg_no|dwg_title|dwg_by|
|1 |153 |153-100 |Pipe... |JS |
表2
|dwg_id|dwg_rev|dwg_date |rev_id|
|1 |A |2015-07-15 11:00:00 |1 |
|1 |B |2015-07-23 12:00:00 |2 |
|1 |C |2015-08-06 10:00:00 |3 |
我想加入两个表,只显示绘图的最新版本更改。
这是我目前的查询。
SELECT
`drawings`.`dwg_id`,
`project_no`,
`sws_dwg_no`,
`client_dwg_no`,
`dwg_title`,
`dwg_by`,
`dwg_rev`.`dwg_rev`,
`dwg_rev`.`dwg_date`,
MAX(`dwg_rev`.`dwg_rev`) AS dwg_rev
FROM
(`drawings`)
JOIN `dwg_rev` ON `drawings`.`dwg_id` = `dwg_rev`.`dwg_id`
WHERE
`project_no` = '153'
GROUP BY
`sws_dwg_no`,
`dwg_rev`.`dwg_rev`
ORDER BY
`dwg_rev`.`dwg_date` ASC,
`dwg_rev`.`dwg_rev` ASC
此查询返回的结果不包含最新的修订号,或者返回每个绘图的所有修订版。
答案 0 :(得分:1)
您可以使用以下查询:
SELECT d.*, dr.*
FROM drawings AS d
INNER JOIN (
SELECT dwg_id, MAX(rev_id) AS maxRevId
FROM dwg_rev
GROUP BY dwg_id
) AS t ON d.dwg_id = t.dwg_id
INNER JOIN dwg_rev AS dr ON t.dwg_id = dr.dwg_id AND t.maxRevId = dr.rev_id
WHERE project_no = 153
上述查询的关键点是使用派生表返回最新版本,即MAX(rev_id)
,每dwg_id
。在该派生表上使用INNER JOIN
,您可以从dwg_rev
表中获取该行。
如果每dwg_id
有多个 project_no
,则必须使用上述内容。在这种情况下,上述查询将获取project_no = 153
每张图纸的最新修订版。
答案 1 :(得分:0)
如果您需要最新版本,请订购以下DESC检查代码。
如果填充此rev_id,您也只能通过dwg_rev .
rev_id` DESC进行订购。
SELECT
附图.
dwg_id ,
project_no ,
sws_dwg_no ,
client_dwg_no ,
dwg_title ,
dwg_by ,
dwg_rev .
dwg_rev ,
dwg_rev .
dwg_date ,
MAX(
dwg_rev .
dwg_rev ) AS dwg_rev
FROM
(
附图)
JOIN
dwg_rev ON
附图{ {1}} dwg_id .
dwg_rev =
dwg_id .
project_no
WHERE
sws_dwg_no = '153'
GROUP BY
dwg_rev ,
dwg_rev .
dwg_rev {{1 }} {dwg_date {1}} {dwg_rev {1}} {dwg_rev {1}}
答案 2 :(得分:0)
有时MAX
不是最佳方式,而是使用LIMIT
试试这个:
SELECT
`drawings`.`dwg_id`,
`project_no`,
`sws_dwg_no`,
`client_dwg_no`,
`dwg_title`,
`dwg_by`,
`dwg_rev`.`dwg_rev`,
`dwg_rev`.`dwg_date`,
`dwg_rev`.`dwg_rev` AS dwg_rev
FROM
(`drawings`)
JOIN `dwg_rev` ON `drawings`.`dwg_id` = `dwg_rev`.`dwg_id`
WHERE
`project_no` = '153'
GROUP BY
`sws_dwg_no`,
`dwg_rev`.`dwg_rev`
ORDER BY
`dwg_rev`.`dwg_date` DESC,
`dwg_rev`.`dwg_rev` DESC
LIMIT 1;