搜索时的高级ORDER BY

时间:2017-01-09 15:43:48

标签: php mysql sql sorting sql-order-by

我们已经建立了一个搜索字段,您可以在其中搜索多种成分并找到食谱。

我们希望根据搜索框中大部分成分的配方对食谱进行分类。

$mors = $db->morsy->findOne([ 'login' => $mojlogin ]);
if (password_verify($mojehaslo, $mors['haslo1'])) {
    // here goes your entrance code
}

可以对它们进行排序吗?

编辑: 配方表

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

$vals = "'" . str_replace(",", "','", $searchquery) . "'";

$query = mysql_query("SELECT * FROM opskrifter WHERE id IN 
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$vals'))") or die("search failed");

成分的表

+---------+----------+-------------+------------+------------+--+
|   id    | name     |  procedure  |  category  |  image_url |  |
+---------+----------+-------------+------------+------------+--+
|       1 | Sausage  | Fry it      | Main dish  | www....com |  |
|       2 | Pizza    | Bake it     | Main dish  | www....com |  |
|       3 | Burger   | Eat it      | Main dish  | www....com |  |
+---------+----------+-------------+------------+------------+--+

更新

我尝试过使用Beginner / Raymond的解决方案:

+---------+----------+-------------+------------+------------+--+
|   id    | recipeid |  ing_num    |  ing_meas  |   ing_name |  |
+---------+----------+-------------+------------+------------+--+
|       1 | 1        | 1           | stack      | sausage    |  |
|       2 | 2        | 200         | g          | wheat      |  |
|       3 | 2        | 100         | g          | beef       |  |
+---------+----------+-------------+------------+------------+--+

"SELECT *, COUNT(*) as `total_ingredients` FROM opskrifter as k , ingredienser as i WHERE k.id = i.opskrifterid AND i.ing_name IN ($vals) GROUP BY k.id ORDER BY COUNT(*) DESC" $vals = "'" . str_replace(",", "', '", $searchquery) . "'";

不幸的是,搜索仅考虑第一个字,例如: "盐,意大利面"它显示每个含盐的配方。但含有这两种成分的配方并不是最重要的配方。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

我面前的答案错过了一个GROUP BY,这就是为什么它只返回一行

SELECT k.id
     , k.name
     , COUNT(*) as `total_ingredients`
  FROM receipts as k
     , ingredients as i
 WHERE k.id = i.receipt_id 
   AND i.ing_name IN ('sausage','beef', 'wheat', 'sauce', 'flour', 'wheat', 'beef', 'ketsup', 'onion', 'garlic')
   GROUP BY k.id, k.name
 ORDER BY COUNT(*) DESC;

JS Fiddle Here

答案 1 :(得分:0)

雅各!

我认为此查询可以解决您的问题。 请试一试。

SELECT k.id
     , k.name
     , COUNT(*) 
  FROM opskrifter k
     , ingredienser i
 WHERE k.id = i.opskrifterid 
   AND i.ing_name IN ('sausage','beef', 'wheat')
 ORDER BY COUNT(*) DESC