sql >> データベース >  >> RDS >> Mysql

MySQLは最新の行のみに参加しますか?

    次のことを試してみてください:

    SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
    FROM      customer c
    JOIN      (
                  SELECT    MAX(id) max_id, customer_id 
                  FROM      customer_data 
                  GROUP BY  customer_id
              ) c_max ON (c_max.customer_id = c.customer_id)
    JOIN      customer_data cd ON (cd.id = c_max.max_id)
    WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
    LIMIT     10, 20;
    

    JOINに注意してください INNER JOINの同義語です 。

    テストケース:

    CREATE TABLE customer (customer_id int);
    CREATE TABLE customer_data (
       id int, 
       customer_id int, 
       title varchar(10),
       forename varchar(10),
       surname varchar(10)
    );
    
    INSERT INTO customer VALUES (1);
    INSERT INTO customer VALUES (2);
    INSERT INTO customer VALUES (3);
    
    INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
    INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
    INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
    INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
    INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');
    

    結果(LIMITなしのクエリ およびWHERE ):

    SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
    FROM      customer c
    JOIN      (
                  SELECT    MAX(id) max_id, customer_id 
                  FROM      customer_data 
                  GROUP BY  customer_id
              ) c_max ON (c_max.customer_id = c.customer_id)
    JOIN      customer_data cd ON (cd.id = c_max.max_id);
    
    +-----------------+
    | name            |
    +-----------------+
    | Mr Bob Smith    |
    | Miss Jane Green |
    | Dr Jack Black   |
    +-----------------+
    3 rows in set (0.00 sec)
    


    1. 制約を変更する方法

    2. JPAを使用したPostgreSQLでのUUIDの永続化

    3. SQLSERVERデータベース内のすべてのテーブルの行数を取得する方法

    4. MySQLまたはMariaDBにデータベースをインポートする