How can I query by a list using SQL?

时间:2015-11-12 11:06:49

标签: sql postgresql

I have a simple table question_to_tag with only two columns tag_id and question_id, the primary key constraint is (tag_id, question_id).

Data stored looks like:

question_id1  | tag_id_2
question_id2  | tag_id_4
question_id3  | tag_id_2
question_id2  | tag_id_1
question_id1  | tag_id_1
question_id1  | tag_id_4

I want to get all the question_id with all tag_id in variable tag_id_list have (question_id, tag_id) in table.

How should I write the SQL?

Sorry all, I mistyped All to Any. Apologized for misleading you.

3 个答案:

答案 0 :(得分:0)

I think that you only need an IN clause :

SELECT question_id FROM question_to_tag WHERE tag_id IN (SELECT tag_id FROM tag_id_list)

Anyway the question is not really clear, so I had to guess the answer ...

答案 1 :(得分:0)

if you format your tag_id_list to be a comma separated value then you can do the following:

SELECT question_id FROM question_to_tag where tag_id in tag_id_list

Now it also depends what you mean by variable, is it in some other programming language? or is it a stored procedure and the variable is an SQL variable.

答案 2 :(得分:0)

Try it like this:

SELECT question_id FROM table WHERE tag_id in (tag_id_list)