以下面的格式提供我的访问表。
ID access value
1 18 ab
1 32 bc
1 48 cd
2 18 ef
3 18 ab
3 32 bc
我需要根据输入获取所有可以访问某些号码的ID。
如果输入为[{access:18,value:ab},{access:32, value:bc}]
select id from access where access = 18 and value ='ab'
intersect
select id from access where access = 32 and value = 'bc'
输出为1,3
如果输入为[{access:18,value:ab},{access:32, value:bc},{access:48,value:cd}]
select id from access where access = 18 and value ='ab'
intersect
select id from access where access = 32 and value ='bc'
intersect
select id from access where access = 48 and value ='cd'
输出为1.
如何以更好的方式编写上述查询,以便根据输入我可以实现所需的结果。
答案 0 :(得分:1)
你的方法很好。另一种方法是:
<form id="comment_form" action="{% url 'operation:update_comment'%}" method="POST" >
{% csrf_token %}
<textarea id="js-pl-textarea"name="comment"></textarea>
<input type="submit" value="Submit"> </input>
</form>
答案 1 :(得分:1)
我认为您将输入作为json数组传递。您可以使用json_to_recordset
将其转换为行,然后使用access
表格进行联接,并将计数与HAVING
进行比较以获得交集。
PostgreSQL 9.6架构设置:
CREATE TABLE access
(ID int, access int, value varchar(2))
;
INSERT INTO access
(ID, access, value)
VALUES
(1, 18, 'ab'),
(1, 32, 'bc'),
(1, 48, 'cd'),
(2, 18, 'ef'),
(3, 18, 'ab'),
(3, 32, 'bc')
;
查询1 :
SELECT ID
FROM access a
INNER JOIN (
SELECT *, COUNT(*) OVER () as ct
FROM json_to_recordset('[{"access":18,"value":"ab"},{"access":32, "value":"bc"}
,{"access":48,"value":"cd"}
]'
)
AS j("access" INT, "value" TEXT)
) j ON (
j.access = a.access
AND j.value = a.value
) GROUP BY ID HAVING COUNT(*) = MAX(ct)
<强> Results 强>:
| id |
|----|
| 1 |