[英]How can I get value from one table and array of values from another join table in one mysql query?
I have a table called lists and a join table called items_to_lists
.我有一个名为列表的表和一个名为
items_to_lists
的连接表。
I want to query and return all lists for a particular user:我想查询并返回特定用户的所有列表:
SELECT lists.* FROM lists WHERE lists.user_id = 'someUserID'
But I also want to include in this query all of the item_id values in the join table as an array for each list.但我也想在这个查询中包含连接表中的所有 item_id 值作为每个列表的数组。 Is this possible?
这可能吗? What I want to be returned is:
我想被退回的是:
list_id = ... , user_id = ... [deck_id1, deck_id2, etc] for each list.
What I have tried is:我尝试过的是:
SELECT lists.*, items_to_lists.item_id FROM lists INNER JOIN items_to_lists ON items_to_lists.list_id = lists.list_id WHERE lists.user_id = 'someUserID'
This returns each relation as a separate row rather than an array associated with each list.这将每个关系作为单独的行返回,而不是与每个列表关联的数组。 Is there anyway to return the list row with an array of the join table item_id's?
无论如何要返回带有连接表 item_id 数组的列表行吗?
GROUP_CONCAT has some more Options like choosing the SEPERAOTR or Ordering the ids GROUP_CONCAT有更多选项,例如选择 SEPERAOTR 或订购 ID
SELECT l.*, CONCAT('[',GROUP_CONCAT(DISTINCT il.item_id) ,']')
FROM lists l INNER JOIN items_to_lists il ON il.list_id = l.list_id
WHERE l.user_id = 'someUserID'
You could use GROUP_CONCAT
with GROUP BY
, something like this:您可以将
GROUP_CONCAT
与GROUP BY
一起使用,如下所示:
SELECT
lists.list_id, GROUP_CONCAT(items_to_lists.item_id)
FROM lists INNER JOIN items_to_lists ON items_to_lists.list_id = lists.list_id
WHERE
lists.user_id = 'someUserID'
GROUP BY
lists.list_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.