在同一查询中搜索不同的表

时间:2016-11-17 04:32:26

标签: php sql

我已经想出如何在同一个表中搜索该表中不同属性的搜索功能。但是,我遇到的一个问题是我无法弄清楚如何在同一个查询中搜索两个或多个不同的表。

我在下面附上了我的查询代码;它只是说查询错了:

    $search= $_POST['searchfun'];

    // Connect database server
    $connection = sqlsrv_connect( $hostName, $connectionInfo )
        or die("ERROR: selecting database server failed");

    //table to store data   
    $userTable = "TRIP";

    // prepare SQL query
    $query = "(
                SELECT * 
                FROM TRIP 
                WHERE DestinationLocation LIKE '%$search%'
                    OR DepartureLocation LIKE '%$search%'
                    OR DepartureTime LIKE '%$search%'
                    OR DestinationTime LIKE '%$search%'
                    OR Distance LIKE '%$search%'
                    OR Cost LIKE '%$search%'
                    OR LicensePlate LIKE '%$search%'
                )
                UNION (
                SELECT * 
                FROM USERS 
                WHERE StudentId LIKE '%$search%'
                    OR FullName LIKE '%$search%'
                    OR SchoolEmail LIKE '%$search%'
                    OR Birthday LIKE '%$search%'
                    OR Username LIKE '%$search%'
                    OR Password LIKE '%$search%'
                    OR Type LIKE '%$search%'
                )";

1 个答案:

答案 0 :(得分:0)

    (
    SELECT * 
    FROM TRIP 
    WHERE DestinationLocation LIKE '%$search%'
       OR DepartureTime LIKE '%$search%'
       OR Distance LIKE '%$search%'
       OR Cost LIKE '%$search%'
       OR LicensePlate LIKE '%$search%'
       OR SchoolEmail LIKE '%$search%'
   )
   UNION
   (SELECT * FROM USERS WHERE SchoolEmail LIKE '%$search%')