スキップしてメイン コンテンツに移動

Java: Identify Country From IP Address

Identify Country From IP Address

Many people sometimes would like to identify country from IP address when you check access log or something.
Most of the people google with keywords like "ip address country" or "whois ip" or something, and then use the internet service which they find.

In this post, I will show you program for identifying country from IP address.
I wrote the program in Java, but if you an average developer you can easily translate into the program language you prefer.


Using File Provided by RIR

IP address is allocated, registered and managed by regional internet registry (RIR).
There are five organization based on covering region:

  • African Network Information Centre (AfriNIC): Africa
  • American Registry for Internet Numbers (ARIN): the United States, Canada, several parts of the Caribbean region, and Antarctica.
  • Asia-Pacific Network Information Centre (APNIC): Asia, Australia, New Zealand, and neighboring countries
  • Latin America and Caribbean Network Information Centre (LACNIC): Latin America and parts of the Caribbean region
  • Réseaux IP Européens Network Coordination Centre (RIPE NCC): Europe, Russia, the Middle East, and Central Asia
The each organization provides the RIR formatted file which tells "Which IP addresses are allocated to which country"
So we use this file, then we can identify country from ip address! bravo!

The RIR file format is quite simple, something like below:

arin|US|ipv4|130.62.0.0|65536|19880609|assigned|f8c82702dc77343cbc6d17c0cb9f76d1

The important parts are:

  • 2nd: country
  • 3rd: type
  • 4th: start ip address
  • 5th: number of ip addresses allocated from the start which is on the 4th column
  • 7th: status
I think you should download the file yourself from the following locations and read the official document here.
Then you can understand much more details rather than my too simplified explanation :P
  • http://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest
  • http://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest
  • http://ftp.apnic.net/pub/stats/apnic/delegated-apnic-extended-latest
  • http://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-extended-latest
  • http://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-extended-latest


Java Code

The program can do below:

  • Download RIR files
  • Create IP address range cache file
  • Check country based on the IP address range cache file
What you should improve:
  • I think you might be better to store the RIR file data or cache file data in database for actual application usage.
  • you should merge some continuous IP ranges for more efficiency. For simplicity, I left it as it is.
Okie. Now I will show you the whole java program for identifying country from ip address.
The advantage of this program is only using Java Standard Development Kit. i.e. no external library required!

Core Code

package com.dukesoftware.utils.net.ipaddress;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

public class IpAddressCountryIdentifier {

    public static void main(String[] args) throws URISyntaxException,
            IOException {
        IpAddressCountryIdentifier checker = new IpAddressCountryIdentifier("c:/temp");
        // you should not call following methods every ip address check
        // updating these files once a day should be fine
        // checker.saveRIRFiles();
        // checker.createIpAddressFileFromRIRFile();
        checker.loadIpAddessToMemory();
        System.out.println(checker
                .guessCountry("ip address which you would like to test here"));
    }

    private static final String[] URLS = new String[] {
            "http://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest",
            "http://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest",
            "http://ftp.apnic.net/pub/stats/apnic/delegated-apnic-extended-latest",
            "http://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-extended-latest",
            "http://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-extended-latest" };

    private final static Map<String, String> FILES = new HashMap<String, String>() {
        {
            Pattern pattern = Pattern.compile("^.+/");
            for (String URL : URLS) {
                String fileBody = pattern.matcher(URL).replaceAll("");
                put(URL, fileBody + ".txt");
            }
        }
    };

    private final Cache cacheV4 = new Cache(
            ipAddressStr -> ipAddressStr.contains("."),
            IpAddressCountryIdentifier::dotIPv4_to_BigInteger);
    
    private final Cache cacheV6 = new Cache(
            ipAddressStr -> ipAddressStr.contains(":"),
            IpAddressCountryIdentifier::colonIpV6_to_BigInteger);
    
    private final String directory;

    public IpAddressCountryIdentifier(String directory) {
        this.directory = directory;
    }

    public void downloadRIRFilesFromNIC() throws IOException {
        for (Entry<String, String> entry : FILES.entrySet()) {
            Utils.saveToFile(entry.getKey(),
                    new File(directory, entry.getValue()).getAbsolutePath());
        }
    }

    public void createIpAddressCacheFileFromRIRFile() throws IOException {
        File ipv4File = new File(directory, "ipv4.txt");
        File ipv6File = new File(directory, "ipv6.txt");

        ipv4File.delete();
        ipv6File.delete();

        for (Entry<String, String> entry : FILES.entrySet()) {
            File file = new File(directory, entry.getValue());
            try (BufferedWriter bwV4 = newWriter(ipv4File);
                    BufferedWriter bwV6 = newWriter(ipv6File)) {
                Utils.processLine(file, line -> {
                    if (line.startsWith("#"))
                        return;

                    String[] parts = line.split("\\|");
                    if (parts.length < 7)
                        return;
                    String status = parts[6];

                    if (!(status.equals("allocated") || status
                            .equals("assigned")))
                        return;
                    String country = parts[1];
                    String type = parts[2];
                    String start = parts[3];
                    long value = 0;
                    try {
                        value = Long.valueOf(parts[4]);
                    } catch (NumberFormatException e) {
                        return;
                    }

                    try {
                        if (type.equals("ipv4")) {
                            bwV4.write(cacheV4.toCacheString(country, start,
                                    value));

                        } else if (type.equals("ipv6")) {
                            bwV6.write(cacheV6.toCacheString(country, start,
                                    value));
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("IOError while reading and writing ip address file", e);
                    }
                });
            }
        }
    }

    public void loadIpAddessToMemory() throws IOException {
        cacheV4.clear();
        cacheV6.clear();
        File ipv4File = new File(directory, "ipv4.txt");
        File ipv6File = new File(directory, "ipv6.txt");

        Utils.processLine(ipv4File, cacheV4::put);
        Utils.processLine(ipv6File, cacheV6::put);
    }

    public String guessCountry(String ipAddress) {
        if (cacheV4.isAcceptableIPString(ipAddress)) {
            return cacheV4.guessCountry(ipAddress);
        }
        if (cacheV6.isAcceptableIPString(ipAddress)) {
            return cacheV6.guessCountry(ipAddress);
        }
        throw new IllegalStateException("Unacceptable ip address format:"
                + ipAddress);
    }

    private static BufferedWriter newWriter(File file)
            throws UnsupportedEncodingException, FileNotFoundException {
        return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                file, true), "utf-8"));
    }
    
    public static BigInteger dotIPv4_to_BigInteger(String dottedIP) {
        String[] addrArray = dottedIP.split("\\.");        
        BigInteger num = BigInteger.ZERO;  
        BigInteger block = BigInteger.valueOf(256);
        for (int i = 0; i < addrArray.length; i++) {            
            int power = 3-i;
            BigInteger value = BigInteger.valueOf(Integer.parseInt(addrArray[i]) % 256);
            value = value.multiply(block.pow(power));
            num = num.add(value);
        }        
        return num;
    }
    
    public static BigInteger colonIpV6_to_BigInteger(String colonedIP) {
        String[] addrArray = colonedIP.split(":", -1);        
        BigInteger num = BigInteger.ZERO;
        BigInteger block = BigInteger.valueOf(65536);
        for (int i = 0; i < addrArray.length; i++) {            
            if(!addrArray[i].equals(""))
            {
                int power = 8-i;
                BigInteger value = BigInteger.valueOf(Long.parseLong(addrArray[i], 16) % 65536L);
                value = value.multiply(block.pow(power));
                num = num.add(value);
            }
        }        
        return num;
    }

}

Class for represents IP address ranges with country

package com.dukesoftware.utils.net.ipaddress;

import java.math.BigInteger;

final class IpRange {
    private final BigInteger start;
    private final BigInteger end;
    private final String country;

    public IpRange(BigInteger start, BigInteger end, String country) {
        this.start = start;
        this.end = end;
        this.country = country;
    }

    boolean inRange(BigInteger value) {
        return value.compareTo(start) >= 0 && value.compareTo(end) <= 0;
    }

    public String getCountry() {
        return country;
    }

}

Class for managing IP Address range cache files

package com.dukesoftware.utils.net.ipaddress;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

class Cache {
    private final List<IpRange> ranges = new ArrayList<>();
    private final Predicate<String> ipStringAcceptor;
    private final Function<String, BigInteger> ipStrToBigInteger;

    public Cache(Predicate<String> ipStringAcceptor,
            Function<String, BigInteger> ipStrToBigInteger) {
        this.ipStringAcceptor = ipStringAcceptor;
        this.ipStrToBigInteger = ipStrToBigInteger;
    }

    void put(String line) {
        String[] parts = line.split("\\|");
        put(parts[0], new BigInteger(parts[1]), new BigInteger(parts[2]));
    }

    private void put(String country, BigInteger start, BigInteger end) {
        ranges.add(new IpRange(start, end, country));
    }

    String guessCountry(String ipAddress) {
        if (isAcceptableIPString(ipAddress)) {
            BigInteger value = ipStrToBigInteger.apply(ipAddress);
            return searchInRange(value, ranges);
        }
        throw new IllegalStateException("Unacceptable ip address format:"
                + ipAddress);
    }

    private static String searchInRange(BigInteger value,
            List<IpRange> ranges) {
        for (IpRange range : ranges) {
            if (range.inRange(value)) {
                return range.getCountry();
            }
        }
        return "";
    }

    public String toCacheString(String country, String start,
            long value) {
        BigInteger startValue = ipStrToBigInteger.apply(start);
        BigInteger endValue = startValue.add(BigInteger.valueOf(value - 1));
        return country + "|" + startValue + "|" + endValue + "\n";
    }

    boolean isAcceptableIPString(String ipAddress) {
        return this.ipStringAcceptor.test(ipAddress);
    }

    void clear() {
        ranges.clear();
    }

}

Class for some trivial utility methods

package com.dukesoftware.utils.net.ipaddress;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Consumer;

public class Utils {
    
    public static final int _1K_BYTES = 1024;

    public final static void saveToFile(String url, String path)
            throws IOException {
        HttpURLConnection urlCon = null;
        try {
            URL urlObj = new URL(url);
            urlCon = (HttpURLConnection) urlObj.openConnection();
            urlCon.setRequestMethod("GET");
            try (InputStream is = urlCon.getInputStream();
                    OutputStream os = new FileOutputStream(path)) {
                byte[] buffer = new byte[_1K_BYTES];
                for (int bytes = 0; (bytes = is.read(buffer)) != -1;) {
                    os.write(buffer, 0, bytes);
                }
                os.flush();
            }
        } finally {
            if (urlCon != null) {
                urlCon.disconnect();
            }
        }
    }
    
    public final static void processLine(File file, Consumer<String> lp) throws IOException{
        try(FileReader in = new FileReader(file);
            BufferedReader br = new BufferedReader(in)){
            String line;
            while ((line = br.readLine()) != null) {
                lp.accept(line);
            }
        }
    }
}

コメント

このブログの人気の投稿

Eclipseでコードカバレッジのハイライトを削除する方法

Eclipseには便利なコードカバレッジ表示機能が搭載されていますが、コード内に緑、赤、黄の色付けがされて煩く感じるときもあると思います。 1度カバレッジの色付けが出てしまった後に消す方法の紹介です(方法は簡単)。 下記のキャプチャの青いマーカーで示した「Remove All Sessions」のボタンを押せばすべて消えます。

「特定の文字から始まらない文字列」にマッチする正規表現

「特定の文字から始まらない文字列」 にマッチする正規表現の例です。  以下の例では、Aから始まらない文字列にマッチする正規表現を示しています。 ^(?!A).*$ 私も正規表現の組み方で四苦八苦することがあります。以下の書籍は実践的に様々な正規表現のパターンを例示してくれているので、重宝しています。

ダイソーで買った200円のドライバーセットでHDDを分解

HDDの処分 最近は個人情報の問題もあって、HDDを処分する前にちゃんとデータの消去を気にすることも多くなってきました。消去方法としては大きく分けて下記の3つがあります。 データ消去ソフトでフォーマット HDD内部のプラッタを物理破壊 データ消去を行ってくれる専門の業者や家電量販店(Sofmapやビックカメラで実施していると思います。費用発生。)に持ち込み。 データ消去ソフトでのフォーマットは簡単ですが、欠点として「フォーマットに時間がかかる」「セクタ破損などで中途半端に壊れたディスクのフォーマットができない」などがあります。 またHDD内部のプラッタの物理破壊については、HDDを分解するために、通常のプラスやマイナスドライバーではなく、星形ネジに対応したトルクスドライバーが必要とのこともあって、少し面倒です。 筆者は今回、今後もHDDの廃棄をするだろうなあと思い、思い切って自分で分解して廃棄することにチャレンジしてみました。(家電量販店に持って行くよりも安くできないかというどケチ丸出しですw) HDDの星形ネジ こんなやつです。ちなみに写真はSeagateのST2000DL003というHDDで撮影しました。 トルクスドライバー というわけで、分解のために Amazonでトルクスドライバー を探しました。 調べると T8のもだと使えそう とのことで、いろいろと物色。 セットのものとか T8一本で立派なやつとか 色々あったのですが、HDD壊すだけで800円かぁ(←どケチ)、と思って購入を躊躇。 ネット上で調べると100円ショップのダイソーでも、トルクスドライバーを販売しているとの情報をキャッチ!近所のダイソーに行って、探したところ星形のヘッド交換に対応した精密ドライバーセットがありました。 プラスが10種類、マイナスが8種類、六角が6種類、星形が6種類(今回ほしかったもの)のセットで、何とお値段税抜き200円!、税抜き200円!と安かったので、ダメもとで購入しました。 結論から言うと 買って大正解 でした。 ダイソーの精密ドライバーセット こんな商品です! 星形対応のヘッドを装着するとこんな感じ。ドライバーのグリップもゴムで滑らない様になっていて使いやす

SQLで特定の文字を組み合わせたランダムな文字列を生成

簡易的な方法として「指定した文字列からランダムに1文字選ぶ」を必要な文字の長さ分concat関数でつなげれば実現できます。 1文字ずつ文字を選ぶので、あまり性能もよくない上、セキュリティ的な観点からのランダム性も担保されていないので、あくまで開発中に必要になった時に使う程度が無難だと思います。 下記に英数字大文字小文字を含んだランダムな3文字の文字列を生成するクエリを示します。 # RAND関数で指定した文字列からランダムに1文字選択。 # 下記の例の62の部分はa~z、A~Z、1~9の文字数の合計値を入れた結果 SELECT CONCAT( SUBSTRING('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', FLOOR(RAND() * 62 + 1), 1), SUBSTRING('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', FLOOR(RAND() * 62 + 1), 1), SUBSTRING('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', FLOOR(RAND() * 62 + 1), 1) ) AS random_string;

PHPの配列(array)のメモリ使用量の考察

はじめに 最近PHP上に大量のデータをメモリ上に展開していたのですが、配列(array)の形式(連想配列 or 単純な配列)や配列の要素のデータ構造(数字、配列、文字列など)で大きくメモリ使用量に差が出てくることに気づき、簡単なプログラムを組んで調べてみました。 あくまで筆者の環境での結果なので、細かい数値は参考程度に見てください。 測定環境と方法 OS: Windows 10 PHP 7.4.5 (php-7.4.5-nts-Win32-vc15-x64) 配列に要素を追加するプログラムを書いて、PHPのmemory_get_usage(true)関数を使って実メモリ使用量を計測しました。 計測結果 No. 方式 1MB当たり作成できる 要素数 プログラム 補足 1 キーも値も整数の配列 (整数IDを想定) 28571 // 2,000,000 / 70MB $row = []; for($i = 0; $i < 2000000; $i++) { $row[] = $i; } No.2~6でテストしたプログラム中の要素数は200,000。これだけ一桁多い! 2 キーが文字列、値が整数の連想配列 8333 // 200,000 / 24MB $row = []; for($i = 0; $i < 200000; $i++) { $row[$i.'_key_string'] = $i; } キーの文字列が長い方がメモリ使用量多くなる。 3 キーが整数、値が連想配列の配列 DBから取得してきたデータを想定 2325 // 200,000 / 86MB $row = []; for($i = 0; $i < 200000; $i++) { row[] = ['id' => $i]; } 4 キーが整数、値が連想配列の配列(配列に複数の値を保持) DBから取得してきたデータを想定 2127 // 200,000 /

ADODB.streamオブジェクトを使って文字列とByte配列を相互変換(Excel VBA)

ADODB.streamオブジェクトを使って文字列をByte配列に変換するコードのサンプルです。 ExcelVBAでADODB.streamを使う際には、 1. ExcelのMicrosoft Visual Basic エディタのメニューバーから「ツール->参照設定」とたどる。 2. 表示されたダイアログからMicrosoft ActiveX Data Objectsにチェックを入れる。 という手順が必要です。 文字列からByte配列へ Private Function ADOS_EncodeStringToByte(ByVal cset As String, ByRef strUni As String) As Byte() On Error GoTo e Dim objStm As ADODB.stream: Set objStm = New ADODB.stream objStm.Mode = adModeReadWrite objStm.Open objStm.Type = adTypeText objStm.Charset = cset objStm.WriteText strUni objStm.Position = 0 objStm.Type = adTypeBinary Select Case UCase(cset) Case "UNICODE", "UTF-16" objStm.Position = 2 Case "UTF-8" objStm.Position = 3 End Select ADOS_EncodeStringToByte = objStm.Read() objStm.Close Set objStm = Nothing Exit Function e: Debug.Print "Error occurred while encoding characters" & Err.Description If objStm Is No

MySQLのSQL_CALC_FOUND_ROWS使用上の注意

MySQLのSQL_CALC_FOUND_ROWSを使用する際の無駄なメモリ消費に注意 ページング機能の実装などのために、ヒットした全件数を取得する必要のある場合があるかと思います。 その場合、下記のようにSQL_CALC_FOUND_ROWSを使うと、検索結果に加えて、そのクエリの全ヒット件数が取得できます。 SELECT SQL_CALC_FOUND_ROWS table.column1, table.column2 ...(途中省略)... FROM table WHERE (条件) しかし、SQL_CALC_FOUND_ROWSを使うと、「絞り込んだ結果にヒットする全べての行の結果のセットを作成する」という大きな欠点があります。 これは、LIMIT, OFFSETを指定していても実行されてしまうので、 SELECTで指定するカラム数やデータ量が多い SELECTの結果返ってくる行数が多い 場合、無駄に領域(≒メモリ)を消費してしまうので注意が必要です。 例えば、100万行検索対象としてヒットするクエリの場合、仮にLIMIT 20と指定して最初の20行を取得するようにクエリを書いても、その100万行分の結果セットが作成されてしまうということになります。 対応策 根本的な対応策としては、SQL_CALC_FOUND_ROWSを使わない(結果行数の取得はCOUNTを用いた別クエリで取得する、結果行数をあらかじめサマリーテーブルに保持しておく)ことですが、 SQL_CALC_FOUND_ROWSをどうしても使う必要がある場合は、 SELECT SQL_CALC_FOUND_ROWS primary_id のように最低限のカラムを指定して結果行セットを取得 (LIMIT OFFSET指定前提) 取得したprimary_idを使って必要なデータを取得 して、SQL_CALC_FOUND_ROWSで使用する領域をできるだけ減らすことで、対応するしかないと思います。 世の中ではLIMIT, OFFSETは使わない方がよいとよく書かれていますが、 SQL_CALC_FOUND_ROWSは、書いてしまえばどんなときも検索にヒットする全結果行セットを作成するので、同じくらい使用する際には注意が必要です。

Visual Studio 2010 SP1のアンインストール

Visual Studio 2013に乗り換えるためにVisual Studio 2010をアンインストールしようとしたところで問題発生。。。 先にVisual Studio 2010本体をアンインストールした後、Visual Studio 2010 SP1をアンインストールできなくて困っていました。 Google先生で調べたところ、以下の情報が見つかり、書かれていた通り実施したところ無事Visual Studio 2010 SP1のアンインストールに成功しました。 How to uninstall/remove Visual Studio SP1 アンインストール手順は以下の通りです。 http://www.microsoft.com/en-gb/download/details.aspx?id=23691 からMicrosoft Visual Studio 2010 Service Pack 1 (Installer)をダウンロード VS10sp1-KB983509.exeというファイル名でダウンロードされる(はず)。 コマンドプロンプトから以下のコマンドを実行 (以下の例は、c:\tempにVS10sp1-KB983509.exeがある場合) c:\temp\VS10sp1-KB983509.exe /uninstall /force ダイアログが立ち上がるので、アンインストールを選択して次へ進めばOK!

WinHttp.WinHttpRequestを使ってHttp PostでByte配列やString配列を送信するプログラム(Excel VBA)

WinHttp.WinHttpRequestオブジェクトを使って使ってHttp PostでByte配列のデータを送信するExcel VBAプログラムです。 WinHttp.WinHttpRequestを使う際には、 1. ExcelのMicrosoft Visual Basic エディタのメニューバーから「ツール->参照設定」とたどる。 2. 表示されたダイアログからMicrosoft WinHTTP Serviceにチェックを入れる。 という手順が必要です。 Byte配列をPOST Private Const BOUNDARY As String = "SOMETHING" Private Function httpPostServletByte(url As String, data() As Byte) As Byte() On Error GoTo e Dim WinHttpReq As WinHttp.WinHttpRequest If (WinHttpReq Is Nothing) Then Set WinHttpReq = New WinHttpRequest End If WinHttpReq.Open "POST", url, False WinHttpReq.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded; boundary=" & BOUNDARY WinHttpReq.send data Dim response() As Byte: response = WinHttpReq.ResponseBody httpPostServletByte = response Set WinHttpReq = Nothing Exit Function e: Set WinHttpReq = Nothing Debug.Print "httpPost Error:" & Err.

MySQL: SELECTの結果をUNIONして ORDER BYする際の最適化方法

SELECTの結果をUNIONして ORDER BY する際には下記の点に注意する必要があります。 無駄なメモリ消費 ソートにINDEXが利かない (≒CPU負荷増大) 対応策 可能であればPush-down Condition (各サブクエリ内でORDER BY, LIMIT, OFFSETを適用してからUNION, ORDER BYを実行する)を利用することで、 パフォーマンスを改善できる場合があります。 下記に例を示します。 もともとのクエリ SELECT tmp.* FROM ( SELECT tableA.column1, tableA.column2 FROM tableA WHERE (条件) UNION ALL SELECT tableB.column1, tableB.column2 FROM tableB WHERE (条件) ) AS tmp ORDER BY tmp.column1, tmp.column2 LIMIT 100, 20 Push-down Conditionを用いて書き直したクエリ SELECT tmp.* FROM ( SELECT tableA.column1, tableA.column2 FROM tableA WHERE (条件) ORDER BY tableA.column1, tableA.column2 LIMIT 30 # <- 10 (offset) + 20 (limit) UNION ALL SELECT tableB.column1, tableB.column2 FROM tableB WHERE (条件) ORDER BY tableB.column1, tableB.column2 LIMIT 30 # <- 10 (offset) + 20 (limit) ) AS tmp ORDER BY tmp.column1, tmp.column2 LIMIT 10, 20 ただしこのPush-down Conditionの手法も下記の場合は、効果が半減しますので注意が必要です。 OFFSETの値が大きい場合は、結局全結果セットUNIONと変わらない サブクエリ内のソートで、INDEXが効かない場合