猿问

MYSQL select 显示匹配和不匹配的记录

我有一个由新行分隔的字符串列表。我需要将这些字符串与单个表中一列中的值进行匹配。问题是我需要将不匹配的记录显示为定义的值,例如“未找到”,因此输出保持与输入相同的长度,并且结果都保持相同的顺序。

示例输入

  1. 苹果

  2. 橘子

  3. 香蕉

期望输出

  1. 苹果存在

  2. 找不到橙色

  3. 梨存在

  4. 香蕉存在

是否可以将自定义值分配给未找到的记录以及在单个语句中找到的显示记录?信息似乎表明我可以使用 IFNULL 创建一个语句来返回不匹配的记录,我已经尝试过这个但无济于事。

 <?php

 // Wrap strings for select statement

 $strings = $_POST['mystrings'];

 $regex = '~<[^>]+>(*SKIP)(*FAIL)|\b\w+\b~'; 

 $strings_wrapped = preg_replace($regex, "'\\0',", $strings);

 $strings_prepared = substr($strings_wrapped, 0, -1);


 // Statement

 $select = "select * from table where specific_row in ($strings_prepared)";


 // Connect

 $connect = mysqli_query($con, $select);


      // Retrieve rows

      while ($row=mysqli_fetch_array($connect)) {

      $column1 = $row['column1'];

      $column2 = $row['column2'];

      $column3 = $row['column3'];

      $column4 = $row['column4'];

      $column5 = $row['column5'];


      // Display results

      $results = "$column1-$column2-$column3-$column4-$column5\n";

      echo $results;

      }

 ?>

匹配的行被正确返回。我只是不知道如何显示不匹配的行。


慕后森
浏览 338回答 2
2回答

慕运维8079593

这是您可以使用的方法:// Statement$select = "select * from table where specific_row in ($strings_prepared)";// Connect$connect = mysqli_query($con, $select);// Retrieve rows$founded = [];while ($row = mysqli_fetch_array($connect)) {&nbsp; &nbsp; $founded[$row['specific_row']] = $row['column1'];&nbsp; // or whatever}foreach ($strings_prepared as $string) {&nbsp; &nbsp; if (!empty($founded[$string])) {&nbsp; &nbsp; &nbsp; &nbsp; echo 'found';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo 'NOT found';&nbsp; &nbsp; }}

一只萌萌小番薯

您可以使用子查询创建包含要搜索的名称的派生表,并将其与表连接。SELECT a.value, IF(b.specific_row IS NULL, 'not found', 'exists') AS foundFROM (&nbsp; &nbsp; SELECT 'apple' AS value&nbsp; &nbsp; UNION&nbsp; &nbsp; SELECT 'orange'&nbsp; &nbsp; UNION&nbsp; &nbsp; SELECT 'pear'&nbsp; &nbsp; UNION&nbsp; &nbsp; SELECT 'banana') AS aLEFT JOIN table AS b ON a.value = b.specific_row
随时随地看视频慕课网APP
我要回答