如何使用一个SQL查询从两个表中获取结果?

我有三个MySQL表

表格1 . dcenter字段是:d_id,名称,位置,地址

表2 . dcds字段是:id,d_id,s_id(d_id和s_id是dcenter和service表的主键)

表3 . 服务字段是:s_id,s_name

我有一个搜索框,用户可以通过dcenter名称搜索,按位置搜索或按服务搜索

我写了一个SQL查询来获取使用JOIN的服务列表,但它无法正常工作

代码是

if(isset($_POST['search']))
{
    $data = $_POST['search_text'];

      $query= "SELECT * FROM dcenter JOIN dcds on dcds.d_id=dcenter.d_id JOIN service on service.s_id=dcds.d_id WHERE location = '" . $data. "' || name = '" . $data. "' || s_name '". $data."'";

        $result = mysql_query($query);

        var_dump($result);

        if(!$result)
        {
            echo "no data found";
        }
       }

我的查询有什么问题?

回答(2)

2 years ago

如果以下SQL返回结果集

SELECT * 
FROM dcenter 
JOIN dcds on dcds.d_id = dcenter.d_id 
JOIN service on service.s_id = dcds.d_id

此WHERE标准添加可以帮助您

SELECT * 
FROM dcenter 
JOIN dcds on dcds.d_id = dcenter.d_id 
JOIN service on service.s_id = dcds.d_id 
WHERE 
    location = '' 
    or name = '' 
    or s_name = ''

2 years ago

试试这个:

SELECT * FROM dcds JOIN dcenter on dcds.d_id=dcenter.d_id JOIN service on service.s_id=dcds.s_id WHERE location = '" . $data. "' || name = '" . $data. "' || s_name '". $data."'";