很抱歉,如果有一种简单的Mysql方法可以做到这一点,但我发现很难说出来获得任何有意义的搜索结果。
我正在搜索我的网站,搜索工作正常,直到我尝试通过基于下拉列表中所选类型的单词进行搜索。
此查询最能代表我正在尝试做的事情:
SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
JOIN bookgenre ON books.BookID = bookgenre.BookID
JOIN genre ON bookgenre.GenreID = genre.GenreID
WHERE genre.Genre = 'Fantasy'
WHERE books.BookName LIKE '%$variable%' OR authors.Forename LIKE '%$variable%' OR authors.Surname LIKE '%$variable%'
GROUP BY books.BookName ORDER BY authors.AuthorID
我想选择所有具有所选类型的书籍,然后从他们那里做其他检查,因为现在让OR覆盖其他检查并最终吐出每个记录。
我猜我可能必须有一个查询选择该类型的所有书籍,然后运行另一个查询以从之前的查询中进行选择。只有我以前从未这样做过,我需要将其纳入我的搜索功能......
这是我当前的搜索代码,除了在尝试搜索选择了“全部”以外的类型的内容时,它的工作正常,如果您只选择一种类型并且不输入任何内容,它将显示该类型的书籍,只是如果你也输入了一个搜索词,那就不行了。
if(isset($_POST['search']))
{
if($_POST['genre']!="All")
{
$where3 = "WHERE genre.GenreID = '".$_POST['genre']."'";
}
if($_POST['field'] == "All")
{
if(str_word_count($_POST['find'])>=2)
{
$findEx = explode(' ', $_POST['find']);
$where2 = "OR authors.Forename LIKE '%".($findEx[0])."%' AND authors.Surname LIKE '%".$findEx[1]."%'";
}
$where = "
WHERE books.BookName LIKE '%".($_POST['find'])."%'
OR authors.Forename LIKE '%".($_POST['find'])."%' OR authors.Surname LIKE '%".($_POST['find'])."%'
$where2
";
}
else if($_POST['field'] == "Books")
{
$where = "WHERE books.BookName LIKE '%".($_POST['find'])."%'";
}
else if($_POST['field'] == "Authors")
{
if(str_word_count($_POST['find'])>=2)
{
$findEx = explode(' ', $_POST['find']);
$where = "WHERE authors.Forename LIKE '%".($findEx[0])."%' AND authors.Surname LIKE '%".$_POST[1]."%'";
}
else
{
$where = "WHERE authors.Forename LIKE '%".($_POST['find'])."%' OR authors.Surname LIKE '%".($_POST['find'])."%'";
}
}
$sql = "SELECT * FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
JOIN bookgenre ON books.BookID = bookgenre.BookID
JOIN genre ON bookgenre.GenreID = genre.GenreID
".$where3."
".$where."
GROUP BY books.BookName
ORDER BY authors.AuthorID";
echo $sql;
}
我对这一切仍然相当新,所以很抱歉,如果我的搜索代码看起来像一场噩梦,它会以最少量的代码完成我所需要的,但欢迎任何提示。
所有帮助表示赞赏-Tom
答案 0 :(得分:0)
也许
SELECT *
FROM Books
JOIN bookauthor ON books.BookID = bookauthor.BookID
JOIN authors ON bookauthor.AuthorID = authors.AuthorID
JOIN bookgenre ON books.BookID = bookgenre.BookID
JOIN genre ON bookgenre.GenreID = genre.GenreID
WHERE genre.Genre = 'Fantasy'
AND books.BookName LIKE '%$variable%' (OR authors.Forename LIKE '%$variable%' OR authors.Surname LIKE '%$variable%')
GROUP BY books.BookName ORDER BY authors.AuthorID