在SQL中找到LEFT JOIN的IN的问题的解决方案 [英] To find a solution to the problem with LEFT JOIN's IN in SQL
问题描述
如何 IN
- 在 ON LEFT JOIN
我尝试选择问题的标题,问题的标签和问题的问题ID来自我的数据库的问题,这样question_id为 14
。我希望问题的标签和标题与question_id 14。
输出应该像
title | question_id | tag
------------ | ---------------------------- | --- --------------
A | 14 | php
A | 14 | perl
A | 14 | sql
A | 14 |数据库
这个问题实际上比起初有更大的挑战。
SELECT questions.title,questions.question_id,tags.tag
FROM questions
LEFT JOIN标签
ON questions.question_id = tags.question_id IN $ b SELECT question_id
FROM questions
DESC LIMIT 50)
WHERE questions.question_id = 14
ORDER BY was_sent_at_time
DESC LIMIT 50;感谢Joe和Tchami在解决第一个问题! >
解决方案您没有为第二个表指定连接条件,因此您要为每个标题选择每个标签。
对行条件使用WHERE
这两个表是如何相关的?将该条件添加到连接。例如
SELECT questions.title,questions.question_id,tags.tag
FROM questions
LEFT JOIN标签
ON questions.question_id = tags.question_id
WHERE questions.question_id = 14
ORDER BY was_sent_at_time
DESC LIMIT 50;
How can you have IN
-clause in ON
-clause with LEFT JOIN
?
I am trying to select the title of a question, tag(s) for the question and question_id for the question from my database such that question_id is 14
. I expect to the tags and title of the question with question_id 14.
The output should look like
title | question_id | tag
------------|----------------------------|-----------------
A | 14 | php
A | 14 | perl
A | 14 | sql
A | 14 | databases
The problem is actually slightly more challenging than initially.
SELECT questions.title, questions.question_id, tags.tag
FROM questions
LEFT JOIN tags
ON questions.question_id = tags.question_id IN ( // Problem here!
SELECT question_id
FROM questions
DESC LIMIT 50 )
WHERE questions.question_id = 14
ORDER BY was_sent_at_time
DESC LIMIT 50;
Thanks to Joe and Tchami in solving the first problem!
解决方案 You haven't specified the join condition for the second table, so you are selecting every tag for every title.
Use WHERE for the row condition
How are the two tables related? Add that condition to the join. For example
SELECT questions.title, questions.question_id, tags.tag
FROM questions
LEFT JOIN tags
ON questions.question_id = tags.question_id
WHERE questions.question_id = 14
ORDER BY was_sent_at_time
DESC LIMIT 50;
这篇关于在SQL中找到LEFT JOIN的IN的问题的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!