[英]Select all values from table B where matches table A
I have this schema: 我有这个架构:
items | taxonomy | subjects
| |
ID headline | item_id subject_id | subject_id subject
-------------------------------------------------------------------------
1 information | 1 1 | 1 cities
2 here we are | 2 1 | 2 towns
3 more things | 3 2 | 3 water
4 doo dah | 3 4 | 4 telephones
| 4 1 |
| 4 3 |
I would like to select a single row from "items" and with it, include all the rows from "subjects" which are joined by the "taxonomy" table. 我想从“items”中选择一行并使用它,包括“subjectonomy”表中连接的“subject”中的所有行。 So for example, getting
item.ID=3
would result in something like: 因此,例如,获取
item.ID=3
将导致类似于:
items.ID = 3
items.headline = "more things"
subjects.subject = "towns"
subjects.subject = "telephones"
I've started with this query 我已经开始使用此查询了
SELECT
i.ID,
i.headline,
s.subject_name
FROM items i
JOIN taxonomy t
on i.ID=t.item_id
JOIN subjects s
on t.subject_id=s.subject_id
WHERE i.ID = 3
But this only returns a single value from subject_name
even if there are multiple values associated with that item_id. 但是这只会从
subject_name
返回一个值,即使有多个与该item_id关联的值也是如此。
EDIT I actually had a LIMIT 1
on the query which was causing (as @Gordon Linoff said) only one row to be returned, even though there were multiple rows in the result set corresponding to the multiple subjects. 编辑我实际上在查询上有一个
LIMIT 1
,导致(如@Gordon Linoff所说)只返回一行,即使结果集中有多行对应多个主题。 His solution still does nicely, because I only want to return a single row. 他的解决方案仍然很好,因为我只想返回一行。
Your query returns the subjects on multiple rows. 您的查询返回多行的主题。 If you want the subjects on a single row, then you need some form of concatenation:
如果您想要单个主题,那么您需要某种形式的连接:
SELECT i.ID, i.headline, GROUP_CONCAT(s.subject_name) as subjects
FROM items i JOIN
taxonomy t
ON i.ID = t.item_id JOIN
subjects s
ON t.subject_id = s.subject_id
WHERE i.ID = 3
GROUP BY i.ID, i.headline;
For one item, the GROUP BY
is optional, but it is good form in case you modify the query to handle multiple items. 对于一个项目,
GROUP BY
是可选的,但如果您修改查询以处理多个项目,它是一个很好的形式。
I would suggest you the "union all" clause (or "union", if you are not needing the duplicates). 我会建议你使用“union all”子句(或“union”,如果你不需要重复项)。
(SELECT
"taxonomy" As Name,
i.headline As Value
FROM items i
JOIN taxonomy t
on i.ID=t.item_id
WHERE i.ID = 3)
Union All
(SELECT
"subject" As Name,
s.subject_name As Value
FROM items i
JOIN subjects s
on t.subject_id=s.subject_id
WHERE i.ID = 3)
You can add a 2nd field in each select to indicate type of item selected ("headline", "subjects", etc). 您可以在每个选择中添加第二个字段以指示所选项目的类型(“标题”,“主题”等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.