MySQL-有条件的MIN MAX返回不同的记录

时间:2019-03-02 17:07:18

标签: mysql sql group-by distinct mysql-5.7

我有一个来自the geonames website for Great Britain的数据库转储。它包含大约60000条记录。 示例数据如下:

id       |     name    |   admin1   |   admin2   |  admin3  |  feature_class  |  feature_code
-------------------------------------------------------------------------------------------
2652355  |   Cornwall  |   ENG      |     C6     |          |      A          |    ADM2
11609029 |   Cornwall  |   ENG      |            |          |      L          |    RGN
6269131  |   England   |   ENG      |            |          |      A          |    ADM1

具有功能代码ADM2的第一条记录表示它是管理级别2 特征代码为RGN的secord记录表示它是一个区域。

我想按地名搜索记录以构建自动完成功能。 如果记录具有相同的名称,并且如果其中一个记录是一个区域,即具有feature_code RGN,那么我只想返回该记录 记录,否则我想返回与ID最低的名称匹配的记录。

我尝试了以下操作,但不起作用:

   SELECT IF(t0.feature_code = 'RGN', MAX(t0.id), MIN(t0.id)) as id
       , CONCAT_WS(', ', t0.name,
                  IF(t3.name != t0.name, t3.name, NULL),
                  IF(t2.name != t0.name, t2.name, NULL),
                  IF(t1.name != t0.name, t1.name, NULL)) AS name
     FROM locations t0
  LEFT JOIN locations t1 ON t1.admin1 = t0.admin1 AND t1.feature_code = 'ADM1'
  LEFT JOIN locations t2 ON t2.admin2 = t0.admin2 AND t2.feature_code = 'ADM2'
  LEFT JOIN locations t3 ON t3.admin3 = t0.admin3 AND t3.feature_code = 'ADM3'
  WHERE 
      (t0.feature_class IN ('P', 'A') OR (t0.feature_class = 'L' AND t0.feature_code = 'RGN' ) )
      AND t0.name like 'Cornwall%' 
  GROUP BY CONCAT_WS(', ', t0.name,
                     IF(t3.name != t0.name, t3.name, NULL),
                     IF(t2.name != t0.name, t2.name, NULL),
                     IF(t1.name != t0.name, t1.name, NULL))
  ORDER BY t0.name 

它返回错误的记录:

id      | name
---------------------------
2652355 | Cornwall, England

3 个答案:

答案 0 :(得分:1)

我认为条件聚合应该可以解决问题。您可以按name过滤记录,然后在集合函数中应用逻辑。如果记录中有feature_code = 'RGN',则您要选择它,否则您将在匹配的记录中选择最小的id

SELECT IFNULL(MAX(CASE WHEN feature_code = 'RGN' THEN id END), MIN(id)) id_found
FROM mytable
WHERE name = @name;
搜索'Cornwall'

Demo on DB Fiddle

| id_found |
| -------- |
| 11609029 |

注意:如果您想要整个匹配的记录,一种解决方案是简单地将上述结果集与原始表进行JOIN

SELECT t.*
FROM mytable t
INNER JOIN (
    SELECT IFNULL(MAX(CASE WHEN feature_code = 'RGN' THEN id END), MIN(id)) id_found
    FROM mytable
    WHERE name = @name
) x ON x.id_found = t.id;

Demo

| id       | name     | admin1 | admin2 | admin3 | feature_class | feature_code |
| -------- | -------- | ------ | ------ | ------ | ------------- | ------------ |
| 11609029 | Cornwall | ENG    |        |        | L             | RGN          |

答案 1 :(得分:0)

在MySQL中,您可以使用相关子查询:

window.addEventListener('load', () => {
  // Determine whether you are going first
  const humanTurnFirst = Math.random() >= 0.5;
  /**
   * Get an array of the text content of each of the tic-tac-toe buttons
   * @returns {Array} Array of the text content of each square, from top-left to bottom-right.
  */

  const getLayout = () => {
    // Array of buttons ordered from top-left to bottom right
    const buttons = [
      document.getElementsByClassName('corner-top-left')[0],
      document.getElementsByClassName('edge-top')[0],
      document.getElementsByClassName('corner-top-right')[0],
      document.getElementsByClassName('edge-left')[0],
      document.getElementsByClassName('center-button')[0],
      document.getElementsByClassName('edge-right')[0],
      document.getElementsByClassName('corner-bottom-left')[0],
      document.getElementsByClassName('edge-bottom')[0],
      document.getElementsByClassName('corner-bottom-right')[0],
    ];
    const layout = [];
    buttons.forEach(button => layout.push(button.innerText));
    return layout;
  };
  /**
   * Make the computer play a square
   * @param {Node} button The square to play
   */

  const autoClick = (button) => {
    console.log('button', button);
    const $turn = document.getElementsByClassName('turn')[0];
    $turn.innerText = 'Not your turn yet...';
    const $allButtons = [...document.getElementsByClassName('button')];
    const $allDisableableButtons = $allButtons
      .filter(
        element => element !== button
        && !element.disabled,
      );
    $allDisableableButtons.forEach((disableableButton) => {
      const thisButton = disableableButton;
      thisButton.disabled = true;
    });
    console.log('button', button);
    button.focus();
    setTimeout(() => {
      button.click();
      $allDisableableButtons.forEach((disableableButton) => {
        const thisButton = disableableButton;
        thisButton.disabled = false;
        $turn.innerText = 'Try clicking an empty space.';
      });
    }, 500);
  };
  /**
   * Calculate the best square for the computer to play.
   * @param {Array.<Node>} layout Array of the text of each square, from top-left to bottom right.
   * @param {Node|Boolean} previous The last move that you've made.
   */
  const computerTurn = (layout, previous, localHumanTurnFirst) => {
    const buttons = [
      document.getElementsByClassName('corner-top-left')[0],
      document.getElementsByClassName('edge-top')[0],
      document.getElementsByClassName('corner-top-right')[0],
      document.getElementsByClassName('edge-left')[0],
      document.getElementsByClassName('center-button')[0],
      document.getElementsByClassName('edge-right')[0],
      document.getElementsByClassName('corner-bottom-left')[0],
      document.getElementsByClassName('edge-bottom')[0],
      document.getElementsByClassName('corner-bottom-right')[0],
    ];
    const $corners = [...document.getElementsByClassName('corner')];
    // If there is no previous move, the computer goes first with a random corner.
    if (!previous) {
      const randomBelow4 = Math.floor(Math.random() * 4);
      const randomCorner = $corners[randomBelow4];
      autoClick(randomCorner);
      /* If the computer is going first,
        has already filled out a random corner,
        and there is nothing in the center,
        it will place another X in one of the adgacent corners.
      */
    } else if (
      !localHumanTurnFirst
      && layout.filter(element => element === 'X').length === 1
      && previous !== buttons[4]
    ) {
      const filledOutCorner = buttons.filter(element => element.innerText === 'X')[0];
      const diagonalCorner = document.getElementsByClassName(filledOutCorner.className
        .split(/\s+/)[2]
        .replace(/(left|right)/, match => (match === 'left' ? 'right' : 'left'))
        .replace(/(top|bottom)/, match => (match === 'top' ? 'bottom' : 'top')))[0];
      const emptyCorners = $corners.filter(corner => corner.innerText === 'Empty');
      const adjacentCorners = emptyCorners.filter(element => element !== diagonalCorner);
      const potentialCorners = adjacentCorners
        .filter(
          corner => document.getElementsByClassName(`edge-${corner.className.split(/\s+/)[2].split('-')[1]}`)[0].innerText === 'Empty'
            && document.getElementsByClassName(`edge-${corner.className.split(/\s+/)[2].split('-')[2]}`)[0].innerText === 'Empty',
        );
      const randomPotentialCorner = potentialCorners[
        Math.floor(
          Math.random()
          * potentialCorners.length,
        )
      ];
      autoClick(randomPotentialCorner);
    } else if (
      !localHumanTurnFirst
      && buttons.filter(button => button.innerText === 'X' && button.className.split(/\s+/).includes('corner')).length === 2
      && buttons.filter(button => button.innerText === 'O' && [...document.getElementsByClassName(`corner-${button.className.replace('button edge edge-', '')}`)].every(element => element.innerText === 'X')).length === 1
    ) {
      autoClick(buttons[4]);
    }
  };
  /**
   * Add event listener for squares
   * @param {Boolean} localHumanTurnFirst Whether you go first.
   */
  const squaresOnClick = (localHumanTurnFirst, isHumanTurn) => {
    const humanLetter = localHumanTurnFirst ? 'X' : 'O';
    const computerLetter = localHumanTurnFirst ? 'O' : 'X';
    const $squares = [...document.getElementsByClassName('button')];
    $squares.forEach((square) => {
      const thisSquare = square;
      square.addEventListener('click', () => {
        if (isHumanTurn) {
          thisSquare.innerText = humanLetter;
          computerTurn(getLayout(), thisSquare, localHumanTurnFirst);
          squaresOnClick(localHumanTurnFirst, false);
        } else {
          thisSquare.innerText = computerLetter;
          squaresOnClick(localHumanTurnFirst, true);
        }
        thisSquare.disabled = true;
      });
    });
  };
  /**
   * Turn the welcome screen into the game screen.
   * @param {Boolean} localHumanTurnFirst Whether you go first.
   */
  const spawnSquares = (localHumanTurnFirst) => {
    const $turn = document.getElementsByClassName('turn')[0];
    const $mainGame = document.getElementsByClassName('main-game')[0];
    $turn.innerText = 'Try clicking an empty space.';
    $mainGame.className = 'main-game dp-4 tic-tac-toe';
    $mainGame.setAttribute('aria-label', 'Tic-tac-toe grid');
    $mainGame.innerHTML = `
      <button class="button corner corner-top-left corner-top corner-left">Empty</button>
      <button class="button edge edge-top">Empty</button>
      <button class="button corner corner-top-right corner-top corner-right">Empty</button>
      <button class="button edge edge-left">Empty</button>
      <button class="button center-button">Empty</button>
      <button class="button edge edge-right">Empty</button>
      <button class="button corner corner-bottom-left corner-bottom corner-left">Empty</button>
      <button class="button edge edge-bottom">Empty</button>
      <button class="button corner corner-bottom-right corner-bottom corner-right">Empty</button>
    `;
    squaresOnClick(localHumanTurnFirst, localHumanTurnFirst);
    if (!localHumanTurnFirst) {
      computerTurn(getLayout(), false, localHumanTurnFirst);
    }
  };
  /**
   * Create the button that starts the game.
   */
  const welcomeButton = (localHumanTurnFirst) => {
    const $welcomeButton = document.getElementsByClassName('start-button')[0];
    $welcomeButton.addEventListener('click', () => spawnSquares(localHumanTurnFirst));
  };
  /**
   * Turn the main game into the welcome screen.
   * @param {Boolean} localHumanTurnFirst Whether you go first.
   */
  const welcome = (localHumanTurnFirst) => {
    const $mainGame = document.getElementsByClassName('main-game')[0];
    const $turn = document.getElementsByClassName('turn')[0];
    $turn.innerText = 'Welcome!';
    $mainGame.className = 'main-game dp-4 welcome center';
    $mainGame.innerHTML = `
    <section class="welcome-section">
      <h2 class="welcome-heading">Welcome to unbeatable tic-tac-toe!</h2>
      <p class="welcome-text">
        According to random chance, your turn has already been chosen
        as ${localHumanTurnFirst ? 'first (with an X)' : 'second (with an O)'}, which 
        means that the computer is going 
        ${localHumanTurnFirst ? 'second (with an O)' : 'first (with an X)'}. <strong>
          Press the start button to start the game!</strong
        >
      </p>
    </section>
    <button class="start-button button">Start</button>
  `;
    welcomeButton(localHumanTurnFirst);
  };
  welcome(humanTurnFirst);
});

在MySQL 8+中,您还可以使用 } else if ( !localHumanTurnFirst && layout.filter(element => element === 'X').length === 1 && previous !== buttons[4] ) { const filledOutCorner = buttons.filter(element => element.innerText === 'X')[0]; const diagonalCorner = document.getElementsByClassName(filledOutCorner.className .split(/\s+/)[2] .replace(/(left|right)/, match => (match === 'left' ? 'right' : 'left')) .replace(/(top|bottom)/, match => (match === 'top' ? 'bottom' : 'top')))[0]; const emptyCorners = $corners.filter(corner => corner.innerText === 'Empty'); const adjacentCorners = emptyCorners.filter(element => element !== diagonalCorner); const potentialCorners = adjacentCorners .filter( corner => document.getElementsByClassName(`edge-${corner.className.split(/\s+/)[2].split('-')[1]}`)[0].innerText === 'Empty' && document.getElementsByClassName(`edge-${corner.className.split(/\s+/)[2].split('-')[2]}`)[0].innerText === 'Empty', ); const randomPotentialCorner = potentialCorners[ Math.floor( Math.random() * potentialCorners.length, ) ]; autoClick(randomPotentialCorner); } else if ( !localHumanTurnFirst && buttons.filter(button => button.innerText === 'X' && button.className.split(/\s+/).includes('corner')).length === 2 && buttons.filter(button => button.innerText === 'O' && [...document.getElementsByClassName(`corner-${button.className.replace('button edge edge-', '')}`)].every(element => element.innerText === 'X')).length === 1 ) { autoClick(buttons[4]); }

select l.*
from locations l
where l.id = (select l2.id
              from locations l2
              where l2.name = l.name
              order by (feature_code = 'RGN') desc,  -- put regions first
                       id asc
             );

答案 2 :(得分:0)

可能存在一种方法,并将所有方法合并在一起

select t1.* from location t1
where exists ( select 1 from location t2 where t2.name=t1.name and t2.feature_code='RGN'
             )
 and t1.feature_code='RGN'
union all

select t1.* from location t1
where not exists ( select 1 from location t2 where t2.name=t1.name and 
                t2.feature_code='RGN'
                  )
  and t1.id=(select min(id) from location t2 where t2.name=t1.name)