【发布时间】:2019-05-16 13:03:46
【问题描述】:
我有 2 个表格,其中插入是由于填写表格。第一个表,称为 data,用 id 注册一行。另一个名为 data_entry 的表注册了几行:表单中的每个字段一个。对于 3 个条目,它给出了类似的内容:
第一张桌子:
data
id
__
1
2
3
第二张桌子:
data_entry
data_id name value
_____________________________________
1 name John
1 age 35
1 email j.smith@smith.com
2 name Alex
2 age 20
2 email alex@dot.com
3 name Kenny
3 age 18
3 email ken62@ggl.com
我的需要
我想在如下表中显示一些数据,仅通过 SQL 请求:
id name email
________________________________
1 John j.smith@smith.com
2 Alex alex@dot.com
3 Kenny ken62@ggl.com
我的临时解决方案
我用一些 PHP 构建我的表,并在一个循环中进行了许多查询,但我想这不是最漂亮(和优化)的解决方案:
$tab = array(); // the table I create
$entries = $this->db->query('SELECT id FROM data'); // the form entries
// for each entry, I create the row in my table
foreach ($entries as $entry) {
// I search for the 3 lines according to the same ID
$query = $this->db->query('SELECT name, value FROM data_entry WHERE data_id = ' . $entry->id );
$line = array('id' => $entry->id);
foreach ($query->result() as $row) { // I build my table's row with each result, except the age not needed
switch ($row->name) {
case 'name':
$line['name'] = $row->value;
break;
case 'email':
$line['email'] = $row->value;
break;
default:
break;
}
}
// now I can build the row in the table
$tab[$entry->id] = $line;
}
有没有更好的方法来获得相同的结果,只使用 SQL,或者只使用一个请求和一点 PHP?
【问题讨论】: