简体   繁体   English

查询具有一对多关系的两个表

[英]Querying two tables with a one to many relationship

I feel a little embarrassed as there is probably an easy solution, but I don't know enough MySQL to do it. 我觉得有点尴尬,因为可能有一个简单的解决方案,但我不知道足够的MySQL来做到这一点。 How do I use one query to get data from each of these tables, and then return an array as illustrated below? 如何使用一个查询从每个表中获取数据,然后返回一个数组,如下图所示? Every attempt I make ends up returning either one tag, or returning multiple arrays of the same task, each with a different tag. 我所做的每一次尝试最终都会返回一个标记,或返回同一任务的多个数组,每个数组都有不同的标记。

What should my query structure look like? 我的查询结构应该是什么样的?

Thanks! 谢谢!

http://i.stack.imgur.com/ViqEs.png http://i.stack.imgur.com/ViqEs.png

The image's array actually shows how the data would look like after two queries, not one. 图像的数组实际上显示了两次查询后数据的外观,而不是一次。 To be able to do it in a single query, and this is because the data is not too complex, you could use a GROUP_CONCAT() to get all of the tags for a task and then use post-query logic to split the data into separate arrays. 为了能够在单个查询中执行此操作,这是因为数据不是太复杂,您可以使用GROUP_CONCAT()获取任务的所有标记,然后使用查询后逻辑将数据拆分为单独的数组。

The SQL query to get all of the requested data would be: 获取所有请求数据的SQL查询将是:

SELECT
    tasks.*, GROUP_CONCAT(tag_name) AS tags
FROM
    tasks LEFT JOIN tags ON tags.task_id=tags.id
WHERE
    id=2

This query will return a single record; 此查询将返回单个记录; in that record, the column tags will hold a comma-separated list of all of the tags that belong to the task. 在该记录中,列tags将保存以逗号分隔的列表,其中包含属于该任务的所有标记。 You can split the data in that column into an array to build your desired structure. 您可以将该列中的数据拆分为数组,以构建所需的结构。

An example, with PHP: 一个例子,用PHP:

$result = mysql_query("SELECT tasks.*, GROUP_CONCAT(tag_name) AS tags FROM tasks LEFT JOIN tags ON tags.task_id=tags.id WHERE id=2");

// create the "$task" array that has a "task" and "tags" index
$task = array('task' => array(), 'tags' => array());
$task['task'] = mysql_fetch_assoc($result);

// split the comma-separated list of tags into an array
$task['tags'] = explode(',', $task['task']['tags']);

// delete the original "tags" entry that's returned by the sql query
unset($task['task']['tags']);

Please note that this example is void of any data validation, connection information, or other logic and should just be used as a rough idea as how you could split the data into your desired structure. 请注意,此示例没有任何数据验证,连接信息或其他逻辑,只能用作如何将数据拆分为所需结构的粗略概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM