首页 > 解决方案 > 为相关的MySql数据库表创建多选过滤系统

问题描述

我的数据库中有 2 个表。

表 1 = wp_bibliography,存储有关期刊文章的信息

+------------+---------+
|  post_id   |  title  |
+------------+---------+
| 1          | Nature  |
| 2          | Science |
| 3          | Neuron  |
+------------+---------+

表 2 = wp_term_relationships,存储不同的标签术语

+------------+---------+
|  object_id |  tag_id |
+------------+---------+
| 1          | 106     |
| 2          | 108     |
| 3          | 106     |
+------------+---------+

post_id 和 object_id 是相关的。

我想创建一个多选复选框,以便我可以返回 108 或 106 或两者的结果。例如,如果我检查 106 和 108,我将返回 post_ids 1、2、3,如果我只选择 106,我将返回 post_ids 1 和 3,如果我选择 108,我只会返回 post_id 2

<div class="list-group-item checkbox">
 <label><input type="checkbox" value="106" >106</label>
 <label><input type="checkbox" value="108" >108</label>
</div>

提交时运行的查询(并且确实有效)如下,但需要动态化(我可以这样做),下面的示例是如果用户同时选择了 106 和 108。

SELECT * 
FROM wp_bibliography x 
JOIN wp_term_relationships y 
ON y.object_id = x.post_id 
WHERE y.term_taxonomy_id IN(106,108) 
GROUP BY post_id HAVING COUNT(*) = 2

我的问题是这是做我想做的最好的方式吗?请注意,我上面的多选复选框将有多达 20 个值,即

HAVING COUNT(*) = 20

有没有更有效,更好的方法来做到这一点?

标签: mysqlsql

解决方案


推荐阅读