简单的子查询?

时间:2014-04-21 03:30:19

标签: php mysql

John 5555

Nancy 5555

Joe 2323

我需要一个简单查询的示例来执行以下操作,以便我可以弄清楚如何操作 将其应用于另一个查询。 THX。

 Search for "John"
 Returns rows John, Nancy

 Search for "Nancy"
 Returns rows John, Nancy

 Search for "Joe"
 Returns rows Joe

这是我到目前为止所做的:

$query = mysqli_query($connect," SELECT *
FROM users
WHERE name like '%$search%'
   (   SELECT number 
      FROM users
      WHERE number like number )
ORDER BY date ASC");

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

假设您的table名称号码

name  |  number
John  |   5555
Nancy |   5555
Joe   |   2323

以下是代码:

<?php

/* ESTABLISH CONNECTION */

$connection=mysqli_connect("YourHost","Username","Password","DatabaseName");

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

if(isset($_POST['submitsearch'])){ /* IF FORM IS SUBMITTED */
   $searchname=mysqli_real_escape_string($connection,$_POST['search']); /* PREVENT SOME OF THE SQL INJECTIONS */
   $result=mysqli_query($con,"SELECT * FROM table WHERE name='$searchname'");
   while($row=mysqli_fetch_array($result)){
   $number=mysqli_real_escape_string($connection,$row['number']); /* GET THE RESPECTIVE NUMBER OF THE SEARCHED NAME */
   }


   /* ECHO THE RESULT HERE */
   echo "<table>";
   $result2=mysqli_query($con,"SELECT * FROM table WHERE number='$number'");
   while($row2=mysqli_fetch_array($result)){ /* FETCH ROWS WITH THE SAME NUMBER COLUMN */
   echo "<tr><td>".$row2['name']."</td></tr>";
   }
   echo "</table>";

}

/* THIS IS YOUR HTML FORM */

echo "<form action='' method='POST'>"; /* SUBMIT ON THE SAME PAGE */
echo "search:<input type='text' name='search'>";
echo "<input type='text' value='search' name='submitsearch'>";
echo "</form>";

?>

答案 1 :(得分:0)

如果我不错过你的要求,你的sql语句应该是这样的:

$sql ="SELECT * FROM user WHERE name LIKE '%$search%' 
OR number IN(SELECT number FROM user WHERE name LIKE '%$search%') 
ORDER BY Date ASC";
$query = mysqli_query($connect,$sql);

希望这对你有所帮助。