我正在处理一个查询,该查询应该通过搜索的关键字返回大多数匹配的数组或标题。不确定即使查询是否应该如此,但它确实有效。不要担心注射,我会在以后再做。这里的目标是返回结果最多的行标题。
$query = "SELECT * ";
$query .= "FROM user_rec ";
$query .= "WHERE sast1 = '" . $mekletie[0] . "'";
$query .= "OR sast1 = '" . $mekletie[1] . "'";
$query .= "OR sast1 = '" . $mekletie[2] . "'";
/*NOTE - the query isn't complete yet, it will run sast2 next and so on until sast5
and compare all the same searched keywords */
$result = mysqli_query($connection, $query);
if (!$result) {
die ("DB query nedarbojas");
}
答案 0 :(得分:0)
好像你想这样做:
$query =
"SELECT *
FROM
(SELECT
u.*,
( sast1 = '" . $mekletie[0] . "' +
sast1 = '" . $mekletie[1] . "' +
sast1 = '" . $mekletie[2] . "' +
sast2 = '" . $mekletie[0] . "' +
sast2 = '" . $mekletie[1] . "' +
sast2 = '" . $mekletie[2] . "' ) AS numberofmatches
FROM user_rec ) m
WHERE
m.numberofmatches > 0
ORDER BY
m.numberofmatches DESC";
但是它不起作用,因为如果sast1
与$mekletie[0]
匹配,那么它将与$mekletie[1]
不匹配,除非它们是相同的,但它在第一个中不是很有用地点。
[编辑] 我看到你的评论,说明还有一个stat2。在这种情况下,您可以使用此方法。但是,如果要为用户存储关键字,您可能需要考虑使用关键字的单独表格,您可以像这样加入:
$query =
"SELECT
u.*
FROM
user_rec u
-- Inner join implicitly excludes users that don't have any matching tag.
INNER JOIN user_tag t ON t.userid = u.userid
WHERE
t.tag IN ('" .$mekletie[0] . "', '" . $mekletie[1] . "', '" . $mekletie[2] . "')
GROUP BY
-- Mysql, unlike other databases, allows you to specify only the id
-- in group by when actually returning other fields as well.
u.userid
ORDER BY
-- You can return the count, or use it just for sorting.
COUNT(t.userid) DESC"