How two join multiple tables with multiple conditions in sqlalchemy - python

select d.field_value as name,a.mobile,c.balance,a.created_at from users as a inner join user_profiles as b on a.id = b.user_id
inner join wallets as c on c.user_profile_id = b.id
left join profile_details as d on d.user_id = a.id where d.field_name = "name" and c.balance > 0 order by a.id desc;
This is my query and i need to write in sqlalchemy, i have model with all mentioned tables and proper columns.
Thanks for yours all efforts and time spent here.

It's pretty easy. I've some links to be referred.
You can refer to the documentation here.
How to join multiple tables here.
How to select only few columns from the query here.
Left and/or right outer join using sqlalchemy here
I think now you may be able to solve your problem. Hope this helps.

Related

SLQ Query - inner join two tables problem

I'm trying to join two tables using SQLite according to unique case id numbers.
If I try running this..
SELECT *
FROM collisions c
INNER JOIN parties p ON c.case_id = p.case_id
WHERE date(collision_date) BETWEEN date('2020-01-01') and date('2021-12-31')
I get an error saying database/disk is full.
I manage to get by creating two databases based on unique ID number, as such..
query_two = """
SELECT *
FROM parties
WHERE date(case_id) BETWEEN '3982887' and '3984887'
"""
query = """
SELECT *
FROM collisions
WHERE date(case_id) BETWEEN '3982887' and '3984887'
"""
and merging them together like this
concat = pd.merge(df_one, df_two, on = 'case_id', how = 'inner')
But this gives me a random sample and it so happens that these case ids include collisions from 2007.
I want to be more specific and join only cases with a specific date range of 2020-01-01 to 2021-12-31.
Note: The parties table doesn't have collision_date - so the only way to join both tables is on case_id.
Is there a workaround to this?
Thanks!

Replacing row values in multiple columns from cascaded table join

I have SQL tables in below format, I was figuring whats the best approach to navigate and join tables to get to the final result. I can do it in Python as well since this seems to require join on multiple columns which would end up duplicating rows.
Any tips?
Table 1:
Table 2 and Table 3 have different number of digits in Account.
Table 2:
Table 3:
Table 1 - With new columns that is needed after navigating from Table 2 and Table 3 to fetch the data into Table1.
You seem to want to combine tables 2 and 3. The logic is not 100% clear, but something like this
with t23 as (
select t2.account, concat(t3.account, ' - ', t3.desc) as desc
from table2 t2 join
table3 t3
on t2.desc = t3.desc
)
select t1.*, t23_1.desc, t23_2.desc, t23_3.desc
from table1 t1 left join
t23 t23_1
on t1.c1 = t23_1.account left join
t23 t23_2
on t1.c2 = t23_2.account left join
t23 t23_3
on t1.c3 = t23_3.account;
I am not sure if t23 is being defined by fiddling with the account column. However, joining on desc seems more obvious.
Also, desc is a very bad name for a column, because it is a SQL keyword (think order by).

SqlAlchemy Outer Join Only Returns One Table

So when I run
select * from table1 t1 left outer join table2 t2 on t1.id = t2.id; in sqlite3 terminal
I get the data back as I want and would expect.
However, when I run this in SqlAlchemy
TableOneModel.query.outerjoin(TableTwoModel,TableOneModel.id == TableTwoModel.id)
I only get table1 information back. I don't even get empty columns from table2. Am I missing something silly?
You're probably using Flask-SQLAlchemy, which provides the query property as a shortcut for selecting model entities. Your query is equivalent to
db.session.query(TableOneModel).\
join(TableTwoModel,TableOneModel.id == TableTwoModel.id)
Either explicitly query for both entities:
db.session.query(TableOneModel, TableTwoModel).\
join(TableTwoModel,TableOneModel.id == TableTwoModel.id)
or add the entity to your original:
TableOneModel.query.\
join(TableTwoModel,TableOneModel.id == TableTwoModel.id).\
add_entity(TableTwoModel)

Any faster way to do mysql update query in R? in python?

I tried to run this query:
update table1 A
set number = (select count(distinct(id)) from table2 B where B.col1 = A.col1 or B.col2 = A.col2);
but it takes forever bc table1 has 1,100,000 rows and table2 has 350,000,000 rows.
Is there any faster way to do this query in R? or in python?
I rewrote your query with three subqueries instead of one - with UNION and two INNER JOIN statements:
UPDATE table1 as A
SET number = (SELECT COUNT(DISTINCT(id))
FROM
(SELECT A.id as id
FROM table1 as A
INNER JOIN table2 as B
ON A.col1 = B.col1) -- condition for col1
UNION DISTINCT
(SELECT A.id as id
FROM table1 as A
INNER JOIN table2 as B
ON A.col2 = B.col2) -- condition for col2
)
My notes:
Updating all of the rows in table1 doesn't look like a good idea, because we have to touch 1.1M rows. Probably, another data structure for storing number would have better performance
Try to run part of the query without update of table1 (only part of the query in parenthesis
Take a look into EXPLAIN, if you need more general approach for optimization of SQL queries: https://dev.mysql.com/doc/refman/5.7/en/using-explain.html

Add a non-FK condition to a LEFT OUTER JOIN in Django ORM to return rows that don't join

I want to run a query of the type:
SELECT company.id
FROM company
LEFT OUTER JOIN employee
ON company.id=employee.company_id AND employee.retired=True
WHERE employee.id IS NULL
IE, I want the database to try to join each company to an employee where retired=True , and to return me the companies that fail to join.
This will give me all companies who don't have a retired employee, including those with no employees.
Is there any way of doing this in Django without using .raw()?
I can do the LEFT JOIN with Company.objects.filter(employee__isnull=True) but I can't add the retired join condition, so I get companies with retired employees. I can't make it a Q(), because in the WHERE clause employee.retired will be NULL. I can do:
Company.objects.exclude(id__in=Employee.objects.filter(retired=True).values('company_id'))
Which is equivalent to the less efficient:
SELECT * FROM company WHERE id NOT IN (SELECT company_id FROM employee WHERE retired=True)
Is there a way of achieving the LEFT JOIN in Django?
Or at least changing the second query to a WHERE NOT EXISTS (SELECT 1 FROM employee WHERE company_id=company.id AND retired=True) so we're filtering the sub-query?
I'm using Django 1.8.5, postgres 9.4 and psycopg2 2.6.1
OK, I don't know a better way to achieve this in one shot, because there's no way to tell django to select ALL employees are not retired. If you think your query would work, just use Company.objects.raw().
Here's my attempt:
no_retired_employees_company = Employee.objects.filter(is_retired=False) \
.values_list('company_id', flat=True).distinct()
no_employee_company = Company.objects.filter(employee__isnull=True) \
.values_list('id', flat=True).distinct()
result = list(a) + list(b)

Categories