将WHERE子句与LIKE和OR

时间:2017-11-03 13:20:26

标签: mysql search where-clause

我的搜索功能有这个sql语句。

$a_search = "$a%";
$sql = "SELECT a.*, u.*
        FROM articles AS a
        LEFT JOIN users AS u
        ON a.written_by = u.username
        WHERE a.written_by OR a.title LIKE ? // want to search for both
        ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
    $stmt->bind_param("s",$a_search);
    $stmt->execute();
    $result = $stmt->get_result();
// more code ...

除了一件事以外,工作正常。它仅搜索a.title匹配的文章。但我也希望通过作者进行搜索,以及我添加a.written_by的原因。但是它仍然只搜索a.title。所以我的问题是如何同时搜索两个

2 个答案:

答案 0 :(得分:1)

你所写的内容在a.written_by上没有任何条件 你必须做像

这样的事情
$a_search = "$a%";
$sql = "SELECT a.*, u.*
        FROM articles AS a
        LEFT JOIN users AS u
        ON a.written_by = u.username
        WHERE a.written_by LIKE ? OR a.title LIKE ? // want to search for both
        ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
    $stmt->bind_param($a_search,$a_search);
    $stmt->execute();
    $result = $stmt->get_result();
// more code ...

这会将结果发送到,其中a.written_by LIKE $ a_search或a.title LIKE $ a_search

答案 1 :(得分:0)

你不能给出一个共同的或者....在每种情况下都要提及......例如。

$a_search = "$a%";
$sql = "SELECT a.*, u.*
        FROM articles AS a
        LEFT JOIN users AS u
        ON a.written_by = u.username
        WHERE a.written_by ='cat' OR a.title LIKE 'dog' ? // want to search 
        ORDER BY a.written_by ASC";
$stmt = $conn->prepare($sql);
    $stmt->bind_param("s",$a_search);
    $stmt->execute();
    $result = $stmt->get_result();
// more code ..