我正在尝试搜索具有给定标记的问题。
如何解决以下问题?
表格
questions | tags
-------------------|-----------------
question_id | tag
title | question_id
was_sent_at_time |
我的代码
SELECT question_id, title
FROM questions
WHERE question_id IN
(
SELECT question_id
FROM questions
ORDER BY was_sent_at_time // problem here
DESC LIMIT 50
)
AND tag IN // problem here
(
SELECT tag FROM tags
WHERE tag = $1
AND WHERE question_id IN (
SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
)
)
ORDER BY was_sent_at_time
DESC LIMIT 50;
我跑步并获得
Warning: pg_prepare() [function.pg-prepare]: Query failed: ERROR: syntax error at or near "WHERE" LINE 14: AND WHERE question_id IN ( ^ in /var/www/codes/handlers/searches/handle_questions_by_tag.php on line 30
我显然应该使用JOIN。 但是,我不想将标签作为输出到我的最终结果。
答案 0 :(得分:3)
尝试:
SELECT q.question_id, q.title
FROM questions q
INNER JOIN tags t ON q.question_id=t.question_id
WHERE tag = $1
ORDER BY q.was_sent_at_time
DESC LIMIT 50
答案 1 :(得分:2)
听起来你只是想要这个:
SELECT questions.question_id, questions.title
FROM questions
WHERE EXISTS
(SELECT 1
FROM tags
WHERE tag = $1 AND tags.question_id = questions.question_id
)
ORDER BY was_sent_at_time DESC
LIMIT 50;
你也可以像JOIN
这样使用:
SELECT questions.question_id, questions.title
FROM questions
INNER JOIN tags ON (tags.question_id = questions.question_id)
GROUP BY questions.question_id
ORDER BY was_sent_at_time DESC
LIMIT 50;
使用JOIN
本身并不能确定您获得的行或列。您可以通过添加适当的SQL子句来确定它。
答案 2 :(得分:1)
JOINS并不意味着您将在最终结果中获得标签。如果您不想看标签,可以保持指定的列相同。
答案 3 :(得分:0)
select questions.* from questions, tags
where questions.questionid = tags.questionid
and tags.tag = $1
但是,我建议在问题和标签之间存在多对多关系(一个问题可以包含许多标签,一个标签可以与许多问题相关联)。
答案 4 :(得分:0)
SELECT questions.question_id, questions.title
FROM questions
INNER JOIN tags ON questions.question_id=tags.question_id
WHERE tags.tag=$1
ORDER BY questions.was_sent_at_time
DESC LIMIT 50;
我认为会这样做......
答案 5 :(得分:0)
怎么样:
SELECT questions.question_id, questions.title, questions.was_sent_at_time
FROM questions
JOIN tags ON questions.question_id = tags.question_id
WHERE tags.tag = 'whatever'
ORDER BY questions.was_sent_at_time
这应该不需要输出中的tags表中的任何内容,尽管我实际上没有测试过它。