简体   繁体   中英

The fastest way to fetch data from the database using codeigniter

There is a table of communications which contains IDs of content and the corresponding keys. It is necessary to organize fast search for a filtration in keys. If value of a key equally to null, approaches any content. For example, if the post inquiry comes $ _POST == array (filter1 => 2, filter2 => 4, filter3 => 2, filter4 => null) , then result will be the array(content_ids => array(4, 7))

id | content_id | filter1| filter2 | filter3 | filter4
1 | 1 | 1 |3 |1 |NULL
2 | 2 | 2 |6 |2 |2
3 | 3 | 1 |5 |1 |NULL
4 | 5 | 1 |1 |1 |5
5 | 4 | 2 |4 |2 |7
6 | 6 | 2 |2 |2 |NULL
7 | 7 | 2 |4 |NULL |NULL

PS: The table will contain thousands of lines, and the number of filters will be equal 12

IMHO the question is more about SQL rather than Codeigniter.

What you can do is to build the query that looks like

SELECT content_id
  FROM table1
 WHERE (? IS NULL OR filter1 = ? OR filter1 IS NULL)
   AND (? IS NULL OR filter2 = ? OR filter2 IS NULL)
   AND (? IS NULL OR filter3 = ? OR filter3 IS NULL)
   AND (? IS NULL OR filter4 = ? OR filter4 IS NULL)

where ? are placeholder for actual filter values that you get via POST .

Output with your sample data:

| CONTENT_ID |
|------------|
|          4 |
|          7 |

Here is SQLFiddle demo

Consider creating a covering index or indices (depending on actual data access patterns) for performance reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM