简体   繁体   English

是否可以在单个mysql查询中使用?

[英]Is this possible in a single mysql query?

I have two tables with a one to many relationship, offer and offer_rows 我有两个具有一对多关系的表,offer和offer_rows

I want to fetch multiple offers with their content rows. 我想获取多个包含其内容行的商品。 That on it's own is not difficult, I just use an 靠它本身并不难,我只是使用

 INNER JOIN on offer.offer_id = offer_rows.offer_id

However, the offer_rows table contains a field called revision and the query needs to always fetch all the rows with the highest revision number. 但是,offer_rows表包含一个称为修订的字段,查询需要始终获取具有最高修订号的所有行。 Is this possible with a single query? 一个查询就能做到吗?

I realize I could change the database design, by adding a third table called offer_revision, I could join this table with a select condition to fetch the latest revision number and then connect this table to the rows. 我意识到我可以通过添加第三个表offer_revision来更改数据库设计,我可以将该表与选择条件结合起来以获取最新的修订号,然后将该表连接到行。 This however would take considerable refactoring so I only want to do it if I have to. 但是,这将需要大量的重构,因此我只在需要时才这样做。

I also want to do this with a direct query - no stored procedures. 我也想直接查询-没有存储过程。

Of course it is possible: 当然有可能:

SELECT o.*, r.revision, r.something_else
FROM offer o,
     offer_rows r
WHERE o.offer_id = r.offer_id
  AND r.revision = (
    SELECT max(revision)
    FROM offer_rows
    WHERE offer_id = o.offer_id
  ) 

You can select all the rows from offer_rows with the MAX(revision) and then JOIN the offer table (no nested query will be required): 您可以选择带有MAX(revision) offer_rows中的所有行,然后JOIN offer表(不需要嵌套查询):

SELECT *, MAX(revision) as latest_revision
FROM offer_rows or
INNER JOIN offer o USING( offer_id )
GROUP BY offer_id

Yes this is possible with a single query. 是的,这可以通过单个查询来实现。 You could have a subquery that get's the highest revision in the WHERE clause. 您可能有一个子查询,该子查询在WHERE子句中得到了最高的修订。

I've used the following comparison to get a latest version entry: 我使用以下比较来获取最新版本的条目:

AND `outer`.`version` = (
    SELECT MAX( `inner`.`version` )
    FROM `content` `inner`
    WHERE `inner`.`id` = `outer`.`id`
    AND `inner`.`language` = `outer`.`language`
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM