我需要一些SELECT
查询逻辑的帮助,希望有人能给我一个比我更好的想法。
我有一张这样的表:
+---------+----------+---------+-----------+
| id | model | variant | category |
+---------+----------+---------+-----------+
| 1 | round | black | fruit |
| 2 | square | white | vegetable |
| 3 | flat | red | meat |
| 4 | round | black | meat |
+---------+----------+---------+-----------+
通过输入一个或多个关键字,用户可以在此表上进行搜索。
我现在的查询对每个字段的所有输入关键字MATCH
执行了AGAINST
,并且获得了与任意关键字匹配的行。
因此,如果输入是“圆肉”,则结果将是第1,3和4行:
SELECT v.*, vt.color
FROM tbl_items
AS v
LEFT JOIN tbl_apple
AS vt
ON v.id = vt.v_id
WHERE (
MATCH (v.model) AGAINST ('keyword1 keyword2' IN BOOLEAN MODE)
OR MATCH (v.variant) AGAINST ('keyword1 keyword2' IN BOOLEAN MODE)
OR MATCH (v.category) AGAINST ('keyword1 keyword2 ' IN BOOLEAN MODE) )
AND v.type = 4
但是,我只需要返回包含ALL关键字的行。关键字可能包含在三列中的任何一列中。
因此,如果用户输入“圆肉”,则仅返回第4行。
我目前的想法很简单,可能不太好(我希望多个关键字有一些性能问题):
SELECT v.*, vt.color
FROM tbl_items
AS v
LEFT JOIN tbl_apple
AS vt
ON v.id = vt.v_id
WHERE
(
(v.model = 'keyword1'
OR v.variant = 'keyword1'
OR v.category = 'keyword1'
)
AND
(v.model = 'keyword2'
OR v.variant = 'keyword2'
OR v.category = 'keyword2'
)
)
AND v.type = 4
有更好的方法吗?
答案 0 :(得分:1)
这是一个可以帮助您的完整代码。" 您可以根据数据库或要求修改查询。
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'test');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(isset($_POST['submit']))
{
$search_text = $_POST['text'];
$values = explode(" ",$search_text);
$query = "";
foreach($values as $value)
{
$query .='concat(model,varient,category) like "%'.$value.'%" AND ';
}
$query .= "1=1";
$query = "select * from tbl_items where ".$query."";
$result= mysqli_query($db,$query);
echo '<table>';
while($row=mysqli_fetch_array($result))
{
echo '<tr>';
echo '<td>'.$row['model'].'</td><td>'.$row['varient'].'</td><td>'.$row['category'].'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
<form method="post" name="form">
<input type="text" name="text" />
<input type="submit" value="submit" name="submit">
</form>