按数据库中选择的值排序

时间:2015-07-31 01:12:57

标签: php

我将如何按照我选择的表中不存在的值进行排序,在这种情况下,值$ count1不在表搜索中。

count具有与其他表中所引用的东西相同的识别ID,这是抓取count1的地方

$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();

$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();

这是来自评级,我将如何排序这样的条目,以便它们基于count1的数量并决定,我可能必须实现类似

$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();

2 个答案:

答案 0 :(得分:0)

可能重复:Mysql order by specific ID values

此处,您只需输出$count1作为逗号分隔字符串,并将其作为ORDER BY FIELD(COUNT,___comma_sep_string___)

添加到SQL查询中

答案 1 :(得分:0)

ratings是一个表,而不是数据库。您可以连接表或使用子查询来获得所需的结果,而无需进行多次查询。

您还没有描述如何在FOREIGN_KEY表中设置ratings,但假设您有ratings.search_id的内容,这应该有效:

SELECT search.*, (SELECT COUNT(rating) 
    FROM ratings 
    WHERE ratings.search_id = search.id 
    AND rating = 'd'
  ) AS rating_count 
FROM search 
WHERE title LIKE '$each'
ORDER BY rating_count