Use another table as WHERE criteria in SQL

I am trying to find questions that have a given tag.

How can you fix the following problem?

Tables

questions          |     tags
-------------------|-----------------
  question_id      |     tag
  title            |     question_id
  was_sent_at_time |

My code

    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;

I run and get

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

I probably should use JOINs. However, I do not want to receive tags as a result for my final result.

+3
source share
6 answers

to try:

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
+3
source

It looks like you just want this:

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;

You can also use JOINlike this:

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;

Usage JOINitself does not determine which rows or columns you get. You define this by adding the appropriate SQL statements.

+2

JOINS , . , .

+1
select questions.* from questions, tags
where questions.questionid = tags.questionid
and tags.tag = $1

( , ).

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;

, ...

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

, .

0

Source: https://habr.com/ru/post/1715351/


All Articles