How can I take several fields from another table in one query?
Let's consider the following code:
=: if(condition: $select_1; condition: $select_2; condition: $select_3; then: 10; else: "")
select_1: select(table: 'table'; field: 'field_1'; where: 'id' = #num)
select_2: select(table: 'table'; field: 'field_2'; where: 'id' = #num)
select_3: select(table: 'table'; field: 'field_3'; where: 'id' = #num)
In this code, we have 3 queries to the same row of the table, but to different fields. It would be much more efficient to fetch all three fields in one query, store them, and reuse them. So, let's do:
=: if(condition: $select[field_1]; condition: $select[field_2]; condition: $select[field_3]; then: 10; else: "")
~select: selectRow(table: 'table'; field: 'field_1'; field: 'field_2'; field: 'field_3'; where: 'id' = #num)
Using selectRow, we fetch multiple fields from a row at once.
We use ~ so that the result is stored upon the first execution, and the subsequent two condition checks do not query the table again.
The result of selectRow is a row that contains 3 values — field_1, field_2, and field_3. To access their values in condition, we use [].
Is it possible to pass a list of fields to selectRow with code?
Yes, there is a fields parameter where we can pass an automatically generated list of fields.
For example, if we want to get the values of all columns, we can retrieve them from the Tables fields table:
=: selectRow(table: 'table'; fields: $sel; where: 'id' = #num)
sel: selectList(table: 'tables_fields'; field: 'name'; where: 'table_name' = "table"; where: 'category' = "column")
How to access an element of a row that we got by code?
Through [] — $select[key].
All standard totum references can be used in square brackets:
e1: $select[$value]
value: "field_1"
e2: $select[#value]
// The value of the field value is field_2
e3: $select[$#nf]
e4: $select[$$row]
row: "key"
key: "field_3"
~select: selectRow(table: 'table'; field: 'field_1'; field: 'field_2'; field: 'field_3'; where: 'id' = #num)
What is the difference in load between multiple select and selectRow
There are different numbers of database queries. Thus, a single selectRow query wins in terms of speed.
Will there be a speed improvement if I forget to put ~ ?
No. If the value is not fixed at the first call, the number of database queries will be the same as when using multiple select statements.