我正在尝试研究如何查询我拥有的表并在select语句中生成特定的输出格式。源表数据如下
+-----------+------------------------+
| prefix_id | Description | A | B |
+-----------+------------------------+
| 55207 | TEST 1 | 1 | 0 |
| 55363 | Test 2 | 1 | 0 |
| 55378 | Test 3 | 0 | 1 |
| 55379 | Test 4 | 1 | 1 |
+-----------+------------------------+
我希望上述数据的输出如下
+-----------+------------+
| A | B |
+-----------+------------|
| TEST 1 | Test 3 |
| Test 2 | Test 4 |
| Test 4 | NULL |
+-----------+------------+
正如您所见,测试4描述出现两次,因为A列和B列都是如此,但顺序并不重要。 NULL字符应仅出现在A列或B列的末尾。只要每个条目在相应列下出现一次,ID就不重要。
也许临时表会有所帮助,但我无法弄清楚如何。对于A列或B列的单独查询很容易,但是将它们合并到输出中是我的问题。
想象一下输出是你在excel中看到的东西,你希望列顶部的数据填充在底部的空白
非常感谢您的帮助。
请注意。希望在SQL查询中实现这一点。使用名为myDBR和Analytics报告工具的东西呈现查询输出。
答案 0 :(得分:1)
您可以在SQL中执行此操作。你要做的是对齐两个列表 - 幸运的是,你不关心顺序(因为你没有列来指定排序)。
以下内容将数据分为两部分,一部分用于“A”列,另一部分用于“B”列。然后它使用MySQL技巧来计算序列号(其他数据库将使用row_number()
)。
以下是查询:
select MAX(A), MAX(B)
from ((select @rn1 := @rn1 + 1 as rn, Description as A, NULL as B
from t cross join (select @rn1 := 0) const
where A = 1
) union all
(select @rn2 := @rn2 + 1 as rn, NULL as A, Description as B
from t cross join (select @rn2 := 0) const
where B = 1
)
) t
group by rn
答案 1 :(得分:0)
简单的数据库查询可以获取所有结果。循环遍历它们以确定它们是属于列A,还是B,或两者。
<?php
// Query all entries from database
$rs = mysql_query('SELECT Description, A, B FROM table ORDER BY Description ASC');
// Loop through all rows in result set
while ( $row = mysql_fetch_assoc( $rs ) ){
// if Column A = 1, add to $colA array
if ( $row['A'] > 0 ) $colA[] = $row;
// if Column B = 1, add to $colB array
if ( $row['B'] > 0 ) $colB[] = $row;
}
现在你需要对数据做些什么。如果您希望以HTML格式显示,或者转换为CSV格式或其他内容,很难从您的问题中判断出来。
但是,现在你的数组$ colA包含与A = 1匹配的行,而数组$ colB包含与B = 1匹配的行。
以下是HTML输出的方法:
<?php
// Setup the base table
$table_html = '<table><tr><th>A</th><th>B</th></tr>';
$x=0;
// Determine which array has more children
if ( count( $colA ) >= count( $colB ) ) {
$use = 'colA'; // A has more
$counter = 'colB';
} else {
$use = 'colB'; // B has more
$counter = 'colA';
}
// The variable variable lets us use either $colA or $colB, as determined by the value in $use.
// More info here: http://php.net/manual/en/language.variables.variable.php
foreach ( $$use as $row ){
// Append the current row, and if its counterpart exists, the other row
if ( $use == 'colA' ){
$table_html .= '<tr><td>' . $row['Description'] . '</td><td>' . ( isset( ${$counter}[ $x ] ) ? ${$counter}[ $x ]['Description'] : '' ) . '</td></tr>';
} else {
$table_html .= '<tr><td>' . ( isset( ${$counter}[ $x ] ) ? ${$counter}[ $x ]['Description'] : '' ) . '</td><td>' . $row['Description'] . '</td></tr>';
}
$x++; // Increment the counter
}
// Close the table
$table_html .= '</table>';
// Output to browser
echo $table_html;