显示来自多个表的数据并按值对其进行分组(PHP / MySQL)

时间:2014-10-13 13:14:53

标签: php mysql

我有几个表,我根据用户输入感觉内部有不同的数据,表格包含不同的列,所以我想创建类似用户活动的页面,向他/她显示他正在做的事情,现在我有几个包含数据的表,我需要以某种方式根据所有表中包含它的一个帐号选择所有数据,并根据日期显示给用户,我现在所拥有的是:

global $wpdb;
global $userInfo;
$il_wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

此示例仅包含2个表,但我有大约6个表,我需要加入它们

$_IL_TABLE_NAME       = $wpdb->prefix . "il_complaints";
$_IL_TABLE_NAME1       = $wpdb->prefix . "il_internal_transfer";
$_IL_GET_COOKIES_VAL = $userInfo['account'];
//my query
$_IL_QUERY_RESULT = $il_wpdb->get_results( "SELECT $_IL_TABLE_NAME.il_date, $_IL_TABLE_NAME1.il_amount FROM $_IL_TABLE_NAME, $_IL_TABLE_NAME1 WHERE $_IL_TABLE_NAME.il_mt4_account='$_IL_GET_COOKIES_VAL' ");
//display data
foreach($_IL_QUERY_RESULT as $_IL_ROW){
    echo $_IL_ROW->il_date;
    echo $_IL_ROW->il_amount;
}

因为数据将在这里从多个表中显示出来,我可以向他们提供一些第一个raw来自第一个表并将其放到表1中,第二行来自第二个表并将其放到表2中,向用户显示他/她做了什么以及从哪里

我将不胜感激。

根据评论尝试

$_IL_QUERY_RESULT = $il_wpdb->get_results( "
SELECT pr_il_complaints.il_date, pr_il_internal_transfer.il_amount
FROM pr_il_complaints t1 INNER JOIN pr_il_internal_transfer t2 ON t1.il_from_mt4 = t2.il_mt4_account;
");

3 个答案:

答案 0 :(得分:0)

你需要一个SQL JOIN,如下所示:

 SELECT t1.name, t2.salary  
FROM employee AS t1 INNER JOIN info AS t2 ON t1.name = t2.name;

SELECT t1.name, t2.salary
FROM employee t1 INNER JOIN info t2 ON t1.name = t2.name;

更多:http://dev.mysql.com/doc/refman/5.0/en/join.html

答案 1 :(得分:0)

试试这个......

$mysqli   = new mysqli("localhost", "username", "password", "database");
$strr     = "SELECT * FROM table1
             INNER JOIN tabel2
              ON table2.account_number = '".$something."'
             INNER JOIN tabel3
              ON table3.account_number = '".$something."'
            "; 
$result   = $mysqli->query($strr);
while($arr      = $result->fetch_array())
{
  echo "<pre>"; print_r($arr);  echo "</pre>"; 
}

答案 2 :(得分:0)

您需要使用联接

SELECT TN.il_date, TN2.il_amount , TNX.field...
FROM $_IL_TABLE_NAME TN
JOIN $_IL_TABLE_NAME1 T2 ON TN.ID_FIELD = TN2.ID_FIELD
JOIN $_IL_TABLE_NAMEX TX ON TX.ID_FIELD = DATABASE.FIELD
JOIN ...
WHERE $_IL_TABLE_NAME.il_mt4_account='$_IL_GET_COOKIES_VAL'

额外信息: 1 .- Sintaxis de JOIN 2 .- Understanding JOINs in MySQL and Other Relational Databases