Home > Database > Mysql Tutorial > How to Replicate CROSS/OUTER APPLY Functionality in MySQL?

How to Replicate CROSS/OUTER APPLY Functionality in MySQL?

DDD
Release: 2024-12-07 13:07:16
Original
460 people have browsed it

How to Replicate CROSS/OUTER APPLY Functionality in MySQL?

CROSS/OUTER APPLY in MySQL

MySQL lacks direct support for the CROSS APPLY syntax, but alternative approaches can be employed to achieve similar functionality.

Nested Sub-query:

In MySQL, a common alternative is to use a correlated sub-query as a predicate in a JOIN statement. This ensures that the sub-query's results are evaluated for each row in the outer query.

Example:

Given the query:

SELECT ORD.ID
    ,ORD.NAME
    ,ORD.DATE
    ,ORD_HIST.VALUE
FROM ORD
CROSS APPLY (
    SELECT TOP 1 ORD_HISTORY.VALUE
    FROM ORD_HISTORY
    WHERE ORD.ID = ORD_HISTORY.ID
        AND ORD.DATE <= ORD_HISTORY.DATE
    ORDER BY ORD_HISTORY.DATE DESC
    ) ORD_HIST
Copy after login

The equivalent query using a nested sub-query would be:

SELECT
   ORD.ID
  ,ORD.NAME
  ,ORD.DATE
  ,ORD_HISTORY.VALUE
FROM
  ORD
INNER JOIN
  ORD_HISTORY
    ON  ORD_HISTORY.<PRIMARY_KEY>
        =
        (SELECT ORD_HISTORY.<PRIMARY_KEY>
           FROM ORD_HISTORY
          WHERE ORD.ID = ORD_HISTORY.ID
            AND ORD.DATE <= ORD_HISTORY.DATE
       ORDER BY ORD_HISTORY.DATE DESC
          LIMIT 1
        )
Copy after login

Direct Sub-query:

In cases where only a single field from the target table is required, a correlated sub-query can be directly integrated into the SELECT statement:

SELECT
   ORD.ID
  ,ORD.NAME
  ,ORD.DATE
  ,(SELECT ORD_HISTORY.VALUE
      FROM ORD_HISTORY
     WHERE ORD.ID = ORD_HISTORY.ID
       AND ORD.DATE <= ORD_HISTORY.DATE
  ORDER BY ORD_HISTORY.DATE DESC
     LIMIT 1
   )   AS VALUE
FROM
  ORD
Copy after login

The above is the detailed content of How to Replicate CROSS/OUTER APPLY Functionality in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template