15.5.8. crate_anon.preprocess.rio_view_func¶
Copyright (C) 2015-2018 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
CRATE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with CRATE. If not, see <http://www.gnu.org/licenses/>.
-
crate_anon.preprocess.rio_view_func.
lookup_from_fragment
(lookup_table: str, aliased_lookup_table: str, lookup_pk: str, basetable: str, basecolumn: str) → str[source]¶ For when lookup_pk is really a PK.
-
crate_anon.preprocess.rio_view_func.
lookup_from_fragment_first_row
(lookup_table: str, aliased_lookup_table: str, lookup_key: str, lookup_unique_field: str, basetable: str, basecolumn: str) → str[source]¶ Modified 2017-01-23, because sometimes the lookup column is not unique, e.g. lookup from “Code” to “CodeDescription” in NNNStatus (see also rio_views.py). The LEFT JOIN was giving us duplicate rows. We want only the first match. See https://www.periscopedata.com/blog/4-ways-to-join-only-the-first-row-in-sql.html
We were doing the FROM component as:
LEFT JOIN {lookup_table} {aliased_lookup_table} ON {aliased_lookup_table}.{lookup_pk} = {basetable}.{basecolumn}
and we’ll replace that with
LEFT JOIN {lookup_table} {aliased_lookup_table} ON {aliased_lookup_table}.{lookup_pk} = ( SELECT {lookup_pk} FROM {lookup_table} WHERE {lookup_table}.{lookup_pk} = {basetable}.{basecolumn} ORDER BY {lookup_table}.{lookup_pk} LIMIT 1 )
… compare to the example of
SELECT * FROM users JOIN widgets ON widgets.id = ( SELECT id FROM widgets WHERE widgets.user_id = users.id ORDER BY created_at DESC LIMIT 1 )
Note that SQL Server uses “SELECT TOP 1 …” not “SELECT … LIMIT 1”.
-
crate_anon.preprocess.rio_view_func.
lookup_from_fragment_first_row_outer_apply
(lookup_fields: Iterable[str], lookup_table: str, aliased_lookup_table: str, lookup_key: str, basetable: str, basecolumn: str) → str[source]¶ As for lookup_from_fragment_first_row, but works without a unique field in the lookup table.
http://stackoverflow.com/questions/2043259/sql-server-how-to-join-to-first-row # noqa http://stackoverflow.com/questions/9275132/real-life-example-when-to-use-outer-cross-apply-in-sql # noqa