Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql查询-条件语句?_Mysql_Sql - Fatal编程技术网

mysql查询-条件语句?

mysql查询-条件语句?,mysql,sql,Mysql,Sql,这是我的桌子: files +----+--------+ | id | name | +----+--------+ | 2 | file_1 | | 3 | file_2 | | 5 | file_3 | +----+--------+ files_already_viewed +----+---------+----------+------+ | id | file_id | category | user | +----+---------+----------+-----

这是我的桌子:

files
+----+--------+
| id |  name  |
+----+--------+
|  2 | file_1 |
|  3 | file_2 |
|  5 | file_3 |
+----+--------+

files_already_viewed
+----+---------+----------+------+
| id | file_id | category | user |
+----+---------+----------+------+
|  1 |       3 |        5 |    1 |
|  2 |       2 |        1 |    1 |
|  3 |       5 |        1 |    1 |
+----+---------+----------+------+

categories_files_join
+--------+---------+
| cat_id | file_id |
+--------+---------+
|      1 |       2 |
|      1 |       5 |
|      5 |       3 |
|      1 |       3 |
+--------+---------+
文件2(其id为3)有两个与之关联的类别,即cat_id 5和cat_id 1

搜索类别5下的文件的用户已查看过一次

但现在用户正在搜索类别1下的文件

我需要一个查询,该查询将不会显示“1”类别下的文件_2,直到类别id为1的所有其他文件都已首先查看,因为用户已查看了文件_2。基本上把文件2放在列表的末尾

以下是我目前的疑问:

SELECT name FROM files
WHERE files.id NOT IN (
    SELECT file_id FROM files_already_viewed
    WHERE user='1')
ORDER BY most_viewed DESC
LIMIT 1
我按最受欢迎的浏览文件进行搜索。但是我不想显示已经被查看过的文件,无论其类别如何,直到所有其他文件都已被该特定类别查看


任何帮助都将不胜感激。谢谢

实际上,您的查询不会显示已经显示的文件。您要做的是对底部已经显示的文件进行排序。因此,基本上,您将需要一组数据:首先,符合所需标准且用户尚未显示的数据,然后是符合所需标准但用户已显示的数据

我处理集合的方法是为每个集合添加一个
customSort
id,然后按它排序。现在简短的解释是,我得到的第一个组是通过一个左连接伪造一个减号运算:我得到了所有还没有看到的文件。然后,第二组比较容易,因为它只需要获取已经看到的所有文件。因此,customSort顺序中两个集合的并集将是您要查找的结果,因此现在您只需要根据当前查询条件筛选该结果(在本例中,category=1)

这里有一个链接。您可以对已查看的文件中插入的每个数据进行注释,以查看查看文件后结果的变化。此外,将
select file_id从
更改为
select*from
将允许您清楚地看到每行属于哪个集合


让我知道这是否有效。

谢谢您的回复,我会尝试一下,然后再报告。
select file_id from (
    select distinct cf1.cat_id, cf1.file_id, 1 as customSort
    from CategoriesFiles1 cf1
    left join FilesViewed1 fv1 on (fv1.file_id = cf1.file_id)
    where (fv1.file_id is null)
    union
    select distinct cf2.cat_id, cf2.file_id, 2 as customSort
    from CategoriesFiles2 cf2
    join FilesViewed2 fv2 on (fv2.file_id = cf2.file_id)
) FinalResult
where (FinalResult.cat_id = 1)
order by customSort