简体   繁体   English

如何做MySQL加入并使用PHP来获取值

[英]How to do MySQL Join and use PHP to get the values

I am trying to write a mysql query to pull data in this format: 我正在尝试编写一个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>

The tables in the database are formatted like the following. 数据库中的表格格式如下。

Table: user_data 表:user_data

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

Table: custom_fields 表:custom_fields

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

Table: custom_field_data 表: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      |
------------------------------------------------------

I am looking for the best solution for querying the data and then printing it to the screen using PHP or AJAX. 我正在寻找查询数据然后使用PHP或AJAX将其打印到屏幕的最佳解决方案。 Is this possible? 这可能吗? Would it be better to use json? 使用json会更好吗? And a sample query would be great. 一个示例查询会很棒。

FYI: In the long run all the data being extracted will need to be filtered on the screen. 仅供参考:从长远来看,所有提取的数据都需要在屏幕上进行过滤。 Thanks for the help. 谢谢您的帮助。

My desired output would be 我想要的输出是

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                |
-------------------------------------------------------------------------------------------------------------------------------------------------------------

You can use the group_concat function, https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat , with my previous query to get a single record per user... 您可以使用group_concat函数https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat与我之前的查询来获取每个用户的单条记录。 。

If you had a SQLfiddle I could test this out but as is I don't have any data to test with... 如果你有一个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

I tested this on 3 tables I have with a similar setup so I think it should work; 我在3个表上测试了这个,我有类似的设置,所以我认为它应该工作; names may need to be tweaked. 名称可能需要调整。

Update: 更新:

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

Lets start with simple join of your custom_field_data to user_data table where values and field names are hardcoded: 让我们从custom_field_datauser_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>

Now, if you want to extract data without hardcoding, you will need to build your SQL dynamically based on data in custom_fields table: 现在,如果要在不进行硬编码的情况下提取数据,则需要根据custom_fields表中的数据动态构建SQL:

SELECT * FROM custom_fields;

If some of your custom fields are never used in relation to users you would want to limit the number of custom fields like this: 如果您的某些自定义字段从未与用户相关,则您希望限制自定义字段的数量,如下所示:

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

Finally, to build required SQL in PHP you need these string sections: 最后,要在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 ..
}

In the end you should get a string with SQL, that will join users to custom_field_data for each available custom field. 最后,您应该获得一个带有SQL的字符串,该字符串将用户连接到每个可用自定义字段的custom_field_data

it is possible o pull the data with $.ajax() and PHP . 可以使用$.ajax()PHP提取数据。 Create a file data.php we are going to load this file with ajax . 创建一个文件data.php我们将用ajax加载这个文件。 In your data.php file write this code. 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>

In your main page use a button to load the data. 在主页面中使用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 在sqlfiddle上的例子

The best way in my opinion is to use join because it will reduce the size of data transferred between DB and PHP 我认为最好的方法是使用join,因为它会减少DB和PHP之间传输的数据大小

You can use JSON as it is light weight. 您可以使用JSON,因为它很轻。

You can keep the things hidden in hidden field and use that for further filtering in client side completely 您可以将事物隐藏在隐藏字段中,并将其用于完全在客户端进行进一步过滤

update -- 更新 -

For Sql server I would have written a query like this 对于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

Change this according to my-sql 根据my-sql改变它

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

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