当查询返回多行时,返回第一行的单个值

时间:2015-11-14 06:37:01

标签: mysql sql codeigniter

下表是我的数据库表格 if(pkt->size>10&&pkt->data[0] ==0 &&pkt->data[1] ==0 &&pkt->data[2] ==0 &&pkt->data[3] ==1 &&(pkt->data[4] == 103 || pkt->data[4] == 104)){ i++; } AVPacket *newPacket = nullptr; // 0 0 0 1 6 8*16 if(i == 2){ i = 0; newPacket = (AVPacket *)av_malloc(sizeof(AVPacket)); av_init_packet(newPacket); newPacket->data = new uint8_t[8]; newPacket->data[0] = 0; newPacket->data[1] = 0; newPacket->data[2] = 0; newPacket->data[3] = 1; newPacket->data[4] = 6; newPacket->data[5] = 123; newPacket->data[6] = 134; newPacket->data[7] = 128; newPacket->size = 8; } av_write_frame(*it , pkt); av_free_packet(pkt); if(newPacket){ av_write_frame(*it , newPacket); av_free_packet(newPacket); }

enter image description here

当我使用此功能传递question时,

$ID=2

结果将是,

enter image description here

我想在结果中返回第一行的function getFirstID($ID) { $checkQ = "SELECT * FROM tabel WHERE quiz_id = '$ID"; $query = $this->db->query($checkQ); if ($query->num_rows() > 0) { return $query->result(); } else { return NULL; } } 。所以输出应该是4。

在我的函数中我应该做什么修改以获得预期的输出?

3 个答案:

答案 0 :(得分:3)

SELECT `ID` FROM tabel WHERE quiz_id = '$ID ORDER BY `ID` LIMIT 1

请尝试此查询。

答案 1 :(得分:3)

在这种情况下,您可以使用ROWNUMLIMITTOPPERCENT

1。)处理行号:

SELECT columnNames FROM Table_name
WHERE ROWNUM <= number;

2.。)可以限制行:

SELECT columnNames FROM Table_name LIMIT number;

3.。)可以从TOP

中选择您想要的行数
SELECT TOP 5 * FROM Table_name;

4.。)可以从以下所有结果中选择百分比:

SELECT  TOP 25 PERCENT * FROM Table_name;

与其他人相比,第4个并不是更好,但我们可以使用它。

关于你的情况,我们可以假设这四个原因:

SELECT * FROM tabel WHERE quiz_id = '$ID AND ROWNUM <= 1;

SELECT * FROM tabel WHERE quiz_id = '$ID AND LIMIT 1;

SELECT TOP 1 * FROM tabel WHERE quiz_id = '$ID;

SELECT 50 PERCENT * FROM tabel WHERE quiz_id = '$ID;

答案 2 :(得分:2)

在CodeIgniter中

 $this->db->select('ID');
 $this->db->from('tabel');
 $this->db->where('quiz_id',$ID);
 $this->db->order_by('ID');
 $q=$this->db->get();
 if ($q->num_rows() > 0) {
        return $q->row();   # Returns single row
    } else {
        return NULL;
    }  

尝试此查询