【问题标题】:How to do MySQL Join and use PHP to get the values如何做 MySQL Join 并使用 PHP 来获取值
【发布时间】:2015-11-01 17:42:42
【问题描述】:

我正在尝试编写一个 mysql 查询来以这种格式提取数据:

<table>
    <caption>table title and/or explanatory text</caption>
    <thead>
        <tr>
            <th>User ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Field Name 1</th>
            <th>Field Name 2</th>
            <th>Field Name 3</th>
            <th>Field Name 4</th>
            <th>Field Name 5</th>
        </tr>
    </thead>
    <tbody>
    <?php 

        while ($row = mysqli_fetch_array($query)) {

        echo "<tr>
                <td>" .$row{'user_id'}. "</td>
                <td>" .$row{'first_name'}. "</td>
                <td>" .$row{'last_name'}. "</td>
                <td>" .$row{'field_name_1'}. "</td>
                <td>" .$row{'field_name_2'}. "</td>
                <td>" .$row{'field_name_3'}. "</td>
                <td>" .$row{'field_name_4'}. "</td>
                <td>" .$row{'field_name_5'}. "</td>
            </tr>";
        }
    ?>
    </tbody>
</table>

数据库中的表格式如下。

表:用户数据

user_id      |     first_name     |    last_name     |
------------------------------------------------------
1            |     Jeff           |    Smith         |
------------------------------------------------------
2            |     Bob            |    Smith         |
------------------------------------------------------
3            |     Steve          |    Smith         |
------------------------------------------------------
4            |     Mary           |    Smith         |
------------------------------------------------------
5            |     Anna           |    Smith         |
------------------------------------------------------

表格:custom_fields

custom_field_id   |    name         |
-------------------------------------
3                 |    field name   |
-------------------------------------
5                 |    field name   |
-------------------------------------
7                 |    field name   |
-------------------------------------
9                 |    field name   |
-------------------------------------
11                |    field name   |
-------------------------------------

表格:custom_field_data

user_id      |     custom_field_id    |    value     |
------------------------------------------------------
1            |     3                  |    XXXX      |
------------------------------------------------------
1            |     5                  |    BBBB      |
------------------------------------------------------
1            |     7                  |    CCCC      |
------------------------------------------------------
1            |     9                  |    ZZZZ      |
------------------------------------------------------
1            |     11                 |    YYYY      |
------------------------------------------------------
2            |     3                  |    XXXX      |
------------------------------------------------------
2            |     5                  |    BBBB      |
------------------------------------------------------
2            |     7                  |    CCCC      |
------------------------------------------------------
2            |     9                  |    ZZZZ      |
------------------------------------------------------
3            |     3                  |    XXXX      |
------------------------------------------------------
3            |     5                  |    BBBB      |
------------------------------------------------------
3            |     9                  |    ZZZZ      |
------------------------------------------------------
3            |     11                 |    YYYY      |
------------------------------------------------------

我正在寻找查询数据然后使用 PHP 或 AJAX 将其打印到屏幕上的最佳解决方案。这可能吗?使用json会更好吗? 一个示例查询会很棒。

仅供参考:从长远来看,所有被提取的数据都需要在屏幕上进行过滤。感谢您的帮助。

我想要的输出是

user_id      |     first_name     |    last_name     |  custom_field_3  |   custom_field_5  |   custom_field_7  |   custom_field_9  |   custom_field_11     |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
1            |     Jeff           |    Smith         |  XXXX            |   BBBB            |   CCCC            |   ZZZZ            |   YYYY                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
2            |     Bob            |    Smith         |  XXXX            |   BBBB            |   CCCC            |   ZZZZ            |   YYYY                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
3            |     Steve          |    Smith         |  XXXX            |   BBBB            |   CCCC            |   ZZZZ            |   YYYY                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
4            |     Mary           |    Smith         |  XXXX            |   BBBB            |   CCCC            |   ZZZZ            |   YYYY                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
5            |     Anna           |    Smith         |  XXXX            |   BBBB            |   CCCC            |   ZZZZ            |   YYYY                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------

【问题讨论】:

  • user_idcustom_field 有什么关系? value 是来自custom_fieldsname?这是加入文档,dev.mysql.com/doc/refman/5.0/en/join.html。应该是可行的,但不确定数据如何关联..
  • 关系就像user_data.user_id -&gt; custom_field_data.user_id -&gt; custom_fields.name ...有意义吗?
  • 起初我误读了问题,以为第三张表是您想要的视图。我想这可能是你在select * from user_data as ud join custom_field_data as cfd on cfd.user_id = ud.user_id join custom_fields as cf on cf.custom_field_id = cfd.custom_field_id 之后的样子
  • @chris85 - 我设法编辑了您的查询,以获得我需要的数据部分。现在的问题是,它为每个自定义字段打印一行......我如何循环并生成上面的 HTML?

标签: php mysql ajax json entity-attribute-value


【解决方案1】:

您可以将group_concat 函数https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat 与我之前的查询一起使用,以便为每个用户获取一条记录...

如果你有一个 SQLfiddle,我可以测试一下,但我没有任何数据可以测试......

select ud.firstname, ud.lastname, group_concat(cf.name) 
from user_data as ud 
join custom_field_data as cfd 
on cfd.user_id = ud.user_id 
join custom_fields as cf 
on cf.custom_field_id = cfd.custom_field_id

我用类似的设置在 3 张桌子上进行了测试,所以我认为它应该可以工作;名称可能需要调整。

更新:

select ud.firstname, ud.lastname, group_concat(cf.name) 
from user_data as ud 
join custom_field_data as cfd 
on cfd.user_id = ud.user_id 
join custom_fields as cf 
on cf.custom_field_id = cfd.custom_field_id
group by ud.user_id

【讨论】:

  • 嘿@chris85,我想我已经接近了。现在我只得到第一行输出。 sqlfiddle.com/#!9/f1e5e/6
  • 添加group by ud.userid sqlfiddle.com/#!9/f1e5e/15。我只测试了 1 条记录,所以以前没有遇到过。
  • 好的 @chris85 - 我在这里工作了,sqlfiddle.com/#!9/88d80/3 - 现在我需要知道如何在 PHP 中获取每个值来打印表格数据。
  • 使用您当前使用的相同获取和回显。使用别名具有与以前相同的列名。
  • 所以在输出的数组中它看起来像这样,pastebin.com/hdRWE77E ...我不确定如何在组合字段时循环遍历它们?就像“27Noe”,其中 27 是 cf id,Noe 是值……有什么帮助吗?
【解决方案2】:

让我们从将 custom_field_data 简单地连接到 user_data 表开始,其中值和字段名称是硬编码的:

SELECT 
 u.*,
 f1.value as "<Field 1 Name>",
 ...
 f2.value as "<Field N Name>"
FROM 
 user_data u LEFT JOIN 
 custom_field_data f1 ON u.user_id = f1.user_id AND f1.custom_field_id = 1
 LEFT JOIN
 custom_field_data f ON u.user_id = fn.user_id AND fn.custom_field_id = <N>

现在,如果您想在不进行硬编码的情况下提取数据,则需要根据custom_fields 表中的数据动态构建 SQL:

SELECT * FROM custom_fields;

如果您的某些自定义字段从未与用户相关,您可能希望像这样限制自定义字段的数量:

SELECT * FROM custom_fields f
WHERE EXISTS 
       (SELECT * FROM custom_field_data 
        WHERE f.custom_field_id = custom_field_id)

最后,要在 PHP 中构建所需的 SQL,您需要以下字符串部分:

// Begin SELECT clause (static):
$sql = "SELECT u.*,"

// Add all fields that you selected form the custom_fields:
foreach ($result as $row) { // Don't forget to handle commas
  $sql = $sql + <expression that gets codes and name>
}

// Start FROM clause (static):
$sql = $sql + " FROM user_data u "


// Join to custom_field_data:
foreach ($result as $row) {
  $sql = $sql + " LEFT JOIN custom_field_data <alias expression> ON ..
}

最后你应该得到一个带有 SQL 的字符串,它会为每个可用的自定义字段将用户连接到custom_field_data

【讨论】:

    【解决方案3】:

    可以使用$.ajax()PHP 提取数据。创建一个文件data.php,我们将使用ajax 加载这个文件。在你的data.php 文件中写下这段代码。

    $query = mysqli_query("select * from custom_field_data 
             inner join 
             user_data on user_data.user_id = custom_field_data.user_id
             inner join 
             custom_fields on custom_field_data.custom_field_id = custom_fields.custom_field_id");
    <table>
    <caption>table title and/or explanatory text</caption>
    <thead>
        <tr>
            <th>User ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Field Name 1</th>
            <th>Field Name 2</th>
            <th>Field Name 3</th>
            <th>Field Name 4</th>
            <th>Field Name 5</th>
        </tr>
    </thead>
    <tbody>
     <?php 
    
        while ($row = mysqli_fetch_array($query)) {
    
        echo "<tr>
                <td>" .$row{'user_id'}. "</td>
                <td>" .$row{'first_name'}. "</td>
                <td>" .$row{'last_name'}. "</td>
                <td>" .$row{'field_name_1'}. "</td>
                <td>" .$row{'field_name_2'}. "</td>
                <td>" .$row{'field_name_3'}. "</td>
                <td>" .$row{'field_name_4'}. "</td>
                <td>" .$row{'field_name_5'}. "</td>
            </tr>";
        }
    ?>
    </tbody>
    

    在您的主页中使用button 来加载数据。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
     <script type="text/javascript">
    $(function(){
        $('#load-data').click(function(){
            $.post('data.php', function(data){
                $('#results').html(data);
            });
        });
    });
    </script>
    

    example on sqlfiddle

    【讨论】:

      【解决方案4】:

      我认为最好的方法是使用 join,因为它会减少 DB 和 PHP 之间传输的数据大小

      您可以使用 JSON,因为它是轻量级的。

      您可以将内容隐藏在隐藏字段中,并完全使用它在客户端进行进一步过滤

      更新--

      对于 Sql server 我会写一个这样的查询

      select 
        t1.user_name,
        t1.first_name,
        t1.last_name,
        (select name from custom_fields 
         where custom_field_id= t2.custom_field_id) 
      from
       user_data t1 left join
       custom_field_data t2 on t1.user_id=t2.userid
      

      根据my-sql改这个

      【讨论】:

      • 谢谢你,Manju,我正在寻找这样的示例查询......有什么想法吗?
      • 这不会产生预期的结果
      • 我已经写了与 sql-server 相关的查询,但不是在 mysql 中
      • 查询是通过牢记逻辑编写的...无论如何我们可以将查询转换为更有效...但它是由逻辑发挥作用
      • 我认为您需要扩展您的答案,因为现在我看不到您的查询结果将如何匹配相关任务。
      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2017-03-03
      • 2012-01-04
      • 1970-01-01
      相关资源
      最近更新 更多