使用SQL和PHP从不同的表中搜索数据

时间:2014-12-01 11:13:45

标签: php mysql sql mysqli

我有4个数据库表(办公室,设施,课程,治疗),办公室表中的id在所有其他3个表中充当办公室ID。

办公室

id  name   address    phoneno  city
1    O1    address1    12      city1
2    O2    address2    34      city2
3    O3    address2    45      city3

设施

id   office_facility   office_id
1       F1              1
2       F2              1
3       F3              2

id   office_course   office_id
1       C1              1
2       C2              2
3       C3              3

治疗

id    office_treatment  office_id
1        T1               1
2        T2               2
3        T3               2

我正试图在设施,课程和治疗的基础上寻找办公室。当只有一个表并且搜索条件是同一个表的一部分时,我工作的搜索代码有效,但这种情况不同。

搜索代码是

<?php
$con=mysqli_connect("localhost","root","","db");// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$city = mysqli_real_escape_string($con, $_POST['city']);

$sql1 = "SELECT * FROM table WHERE city LIKE '%$city%'";
$result = mysqli_query($con, $sql1);

if (mysqli_num_rows($result) > 0) 
    {
        while($row = mysqli_fetch_assoc($result)) {
        echo "Office name: " . $row["office_name"]. " - Location: " . $row["office_address"]. " " . $row["office_city"]. "<br>";
    }
} else {
    echo "0 results";
}
mysqli_close($con);
?>

如果有人能告诉我如何从这些表中搜索办公室,我将不胜感激

3 个答案:

答案 0 :(得分:0)

您可能希望对数据库执行复杂的SQL查询,并连接所有条件:

SELECT address FROM office
  JOIN facility ON (facility.office_id = office.id)
  JOIN course ON (course.office_id = office.id)
  JOIN treatment ON (treatment.office_id = office.id)
WHERE city LIKE %...% 
  AND office_facility LIKE %...%
  AND office_course LIKE %...%
  AND office_treatment LIKE %...%

LIKE / AND上的OR以及布尔逻辑的值现在由您决定。

答案 1 :(得分:0)

你可以使用union

select A.ID,(SELECT B.Name from office B where A.ID=B.ID) as Name from (

select id  from office where <Your Office Table filter Criteria>

UNION 

select office_id from facility where <Your facility Table filter Criteria>

UNION 

select office_id from Course where <Your Course Table filter Criteria>

UNION 

select office_id from Treatment where <Your Treatment Table filter Criteria>
)A

答案 2 :(得分:0)

您可以使用联接查询。实际上你还没有说明你需要什么,所以我试图给你相同的基本(全局)例子

"select from table_name as td 
left join anoather_table as anoth on td.common_column = anoth.commoncolun whare td.condition_columh= condition"