简体   繁体   English

如何根据另一个表中的值过滤SQL查询

[英]How to filter SQL query based on value in another table

I'm new to SQL queries and are trying to figure out how to filter my output somehow. 我是SQL查询的新手,正在尝试弄清楚如何以某种方式过滤我的输出。

The function I want to achieve is that multiple users can be listed as authors on a single entry, AND, also the possibility to filter the search result by using a drop-down menu or something like that to see which entries an author is listed too. 我要实现的功能是可以将多个用户列为单个条目中的作者,并且,还可以通过使用下拉菜单或类似的东西来过滤搜索结果,以查看列出了哪些作者的条目。

I currently have two tables in my database, one is called ENTRIES and the other is AUTHORS 我目前在数据库中有两个表,一个表称为ENTRIES,另一个表为AUTHORS

Each of the tables looks like this: 每个表如下所示:

+-------------------------------+       +---------------------------------+
DB: ENTRIES // To keep all entries.     DB: AUTHORS // To keep track of which authors that are listed to each entry.
+-------------------------------+       +---------------------------------+
ID   TITLE    DATE                      ID   AUTHOR1    AUTHOR2    AUTHOR3
1    NAME     2018-03-19                1    TRUE       FALSE      TRUE
2    NAME     2018-03-20                2    FALSE      TRUE       FALSE
3    NAME     2018-03-21                3    TRUE       FALSE      FALSE
+-------------------------------+       +---------------------------------+

My SQL query looks like this right now: 我的SQL查询现在看起来像这样:

$query = "
 SELECT * FROM ENTRIES INNER JOIN AUTHORS ON ENTRIES.ID=AUTHORS.ID;
 ";
}
$result = mysqli_query($con, $query);

I get it to list all the results but I don't know how to filter the results based on the value in the AUTHORS table? 我得到它列出所有结果,但是我不知道如何根据AUTHORS表中的值过滤结果? And are INNER JOIN the right way to go? 而且INNER JOIN是正确的方法吗?

The result should be something like: 结果应该是这样的:

FILTER ON: ALL / NAME / NAME / NAME

#####################################################
# 1  TITLE     AUTHOR 1 AUTHOR 3         DATE       #
#####################################################

#####################################################
# 2  TITLE     AUTHOR 2                  DATE       #
#####################################################

#####################################################
# 3  TITLE     AUTHOR 1                  DATE       #
#####################################################

You have to use subqueries. 您必须使用子查询。

SELECT * FROM entries e
WHERE EXISTS(SELECT id FROM authors a WHERE e.id = a.id)

https://dev.mysql.com/doc/refman/5.7/en/subqueries.html https://dev.mysql.com/doc/refman/5.7/zh-CN/subqueries.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM