How do I get all the 'name' column corresponding to the supplied ids in a single query ?
Suppose I have a php array like this
$ids = [ '1', '3', '7', '24', ... ];
then, is it possible to get the 'name' in the following table WHERE $ids[i]='id'
in that table, all in a single query, or do I need to use for
loop ?CREATE TABLE `services` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '',
`description` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`) USING BTREE
)
I am working with CodeIgniter.
Answer:
You can use
where_in
for this$ids = [ '1', '3', '7', '24', ... ];
$this->db->select('name');
$this->db->from('services');
$this->db->where_in('id', $ids);
you can use IN clause
SELECT * FROM `services` WHERE ID IN (".implode(',' , $ids).");
In case the dataType is varchar , make sure to add '
accordingly
SELECT * FROM `services` WHERE ID IN ('".implode('','' , $ids)."');
0 nhận xét:
Đăng nhận xét