php - 使用 PHP/MySql 中的单个查询从多个表中获取 'related' 数据?

标签 php mysql sql database pdo

我正在从头开发一个小型 PHP 应用程序来练习/学习。目标是能够创建文章。每篇文章都可以有标签和图像,存储在它们自己的表中。 由于一篇文章可以有多个标签,而一个标签可以出现在多篇文章中,因此我还创建了一个“标签/文章”关联表。

现在,当我想编辑或显示一篇文章时,我通​​过执行多个数据库请求来获取它的数据(加上标签和图像)...例如,给定一个文章 ID,我会执行如下操作:

$article = getArticle($articleId);
$tags = getArticleTags($articleId);
$images = getArticleImages($articleId);

它有效,但我不确定它是否是一种干净的方法和良好的性能。 所以我想知道,这可以通过使用单个查询来完成吗? 我尝试过,但对 UNION 和 JOIN 有点困惑。 如果没有,是否有更好/推荐的方法来实现这一目标?

我使用的(简化的)表格是:

文章表:

┌-----┬------------------┬------------------------┐
│ id  │ title            │ dateCreated            │
├-----┼------------------┼------------------------┤
│ 1   │ some article     │ 2015-03-17 12:38:49    │
├-----┼------------------┼------------------------┤
│ 2   │ article two      │ 2015-03-17 15:00:24    │
└-----┴------------------┴------------------------┘ 

标签表:

┌-----┬------------------┬------------------------┐
│ id  │ name             │ dateCreated            │
├-----┼------------------┼------------------------┤
│ 1   │ php              │ 2015-03-17 15:01:05    │
├-----┼------------------┼------------------------┤
│ 2   │ jquery           │ 2015-03-17 15:24:12    │
└-----┴------------------┴------------------------┘ 

标签-文章关联表:

┌-----┬--------┬-------------┬------------------------┐
│ id  │ tagId  │ articleId   │ dateCreated            │
├-----┼--------┼-------------┼------------------------┤
│ 1   │ 1      │ 1           │ 2015-03-17 15:01:06    │
├-----┼--------┼-------------┼------------------------┤
│ 2   │ 2      │ 1           │ 2015-03-17 15:24:58    │
├-----┼--------┼-------------┼------------------------┤
│ 3   │ 1      │ 2           │ 2015-03-17 15:30:38    │
└-----┴--------┴-------------┴------------------------┘

文章图片表:

┌-----┬-----------┬-------------┬------------------------┐
│ id  │ fileName  │ articleId   │ dateCreated            │
├-----┼-----------┼-------------┼------------------------┤
│ 1   │ pic1.jpg  │ 1           │ 2015-03-17 16:05:26    │
├-----┼-----------┼-------------┼------------------------┤
│ 2   │ pic2.jpg  │ 1           │ 2015-03-17 16:06:29    │
├-----┼-----------┼-------------┼------------------------┤
│ 3   │ dog.jpg   │ 2           │ 2015-03-17 17:00:14    │
├-----┼-----------┼-------------┼------------------------┤
│ 4   │ cat.jpg   │ 2           │ 2015-03-17 17:01:06    │
├-----┼-----------┼-------------┼------------------------┤
│ 5   │ bird.jpg  │ 2           │ 2015-03-17 17:02:34    │
└-----┴-----------┴-------------┴------------------------┘

此外,我正在以这种方式使用 PDO,例如,获取一篇文章:

    public function getArticleById($id){
        $sql = "SELECT * FROM articles WHERE id=:id LIMIT 1";
        $query = $this->db->prepare($sql);
        $parameters = array(':id' => $id);
        $result = $query->execute($parameters);
        return ($result) ? $query->fetch() : 0;
    }

任何输入将不胜感激。谢谢!


更新:

@Adrian 的回答接近我正在寻找的内容并且部分解决了问题。它返回以下 enter image description here

问题是 id 列不明确,我无法弄清楚如何以这样一个干净的数组结束,理想情况下:

Array
(
    [title] => some article
    [id] => 1
    [tags] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => php
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => jquery
                )

        )

    [images] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [fileName] => pic1.jpg
                )

            [1] => Array
                (
                    [id] => 2
                    [fileName] => pic2.jpg
                )

        )

)

然后,结合 Daniel 和 Adrian 的回答,我得到了这个查询,它返回了一些更具可读性的东西(我猜)我可以处理以实现上述数组(我想迭代和删除重复项):

SELECT 
    a.id, 
    a.title, 
    a.dateCreated as articleDate,
    i.id as imageId,
    i.fileName as imageFile,
    t.id as tagId,
    t.name as tagName
FROM 
    articles a
JOIN 
    article_tags ta ON a.id = ta.articleId
JOIN
    tags t ON ta.tagId = t.id

JOIN 
    images i ON a.id = i.articleId


WHERE 
    a.id = 1

返回:

enter image description here

在性能方面,因为这种可能的解决方案会返回许多包含重复数据的行(取决于与文章关联的标签和图像的数量)。 这比我开始时进行的初始多次调用更好吗?

最佳答案

SELECT 
    a.id, 
    a.title, 
    a.dateCreated as articleDate,
    i.fileName as imageFile,
    t.name as tagName
FROM 
    articles a
JOIN 
    images i ON a.id = i.articleId
JOIN 
    tag_article ta ON a.id = ta.articleId
JOIN
    tags t ON ta.articleId = t.id
WHERE 
    a.id = ?

关于php - 使用 PHP/MySql 中的单个查询从多个表中获取 'related' 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29113319/

相关文章:

sql - 如何编写 SQL 查询来生成报告

php - 如何在 php 中检查当前 url

php - 命令 "tinker"未定义

php - MySQL选择3个随机行,其中三行之和小于值

mysql - 使用子选择查询运行缓慢

SQL Server : replace year of datetime with current year in Select

php - Laravel:如何验证 DB::transaction 函数是否正常工作?

php - 使用 codeigniter 在查询中获取额外报价

java - MySQL 和 SQLite 类

MySQL innodb b-tree 在后台重新平衡异步或在需要重新平衡时完成每次写入操作