Convert PostgreSQL to SqlAlchemy query - sql

I have a simple query in PostgreSQL which I need to convert to SQLAlchemy.
SELECT table1.name,table2.ip,table2.info
FROM table1 LEFT OUTER JOIN table2
ON(table1.name=table2.hostname)
GROUP BY table1.name;
I have tried using this with no success:
session.query(table1.name
,table2.ip
,table2.info).distinct().join(table2).group_by(table1.name)
Can someone please help me with this?
Thanks in advance
Ishwar

Here's how you would do it using the Expression API
http://docs.sqlalchemy.org/en/latest/core/expression_api.html
Define your table, for example:
table1 = table('table1',
column('name', String())
)
table2 = table('table2',
column('ip', String()),
column('info', String()),
column('hostname', String()),
)
Compose your query, like:
my_query = select([table1.c.name,
table2.c.ip,
table2.c.info]
).select_from(
table1.outerjoin(table2, table1.c.name == table2.c.hostname)
).group_by(table1.c.name)
Execute your query, like:
db.execute(my_query)

It's not clear from your answer what the problem is, but my shoot at this query would be:
session.query(table1.name
,table2.ip
,table2.info)\
.outerjoin(table2)\
.group_by(table1.name)

I figured out the answer. I was actually missing the ON condition in query:
session.query(table1.name
,table2.ip
,table2.info
).distinct().outerjoin(table2 , table1.name=table2.hostname
).group_by(table1.name)
Thanks for help!

Related

changing sql statement to eloquent query

So I have an SQL statement as such;
AND created_at BETWEEN '20190601' and '20190630'
How do I change this to an eloquent query? Or is it better to just use a db:raw query?
All inputs are very much appreciated. Cheers!
You can try this :
$yourQuery->whereBetween('created_at', ['20190601', '20190630']);
Read more at whereBetween section in here
As you are comparing dates, then do this:
$fromDate = '20190601';
$toDate = '20190630';
$yourquery->whereBetween('created_at', array($fromDate->toDateTimeString(), $toDate->toDateTimeString()) )->get();

How to convert SQL Query to CodeIgniter?

How to convert this query :
SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;
I have try many code, and i still got undefine.
Try this
$query = $this->db->select('pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah')
->from('pembelian_detail_tb')
->join('produk_tb', 'pembelian_detail_tb.kode_produk = produk_tb.kode_produk', 'inner')
->get();
I like to use Query Bindings once a join is involved in a query:
https://www.codeigniter.com/userguide3/database/queries.html
search page for "query bindings"
this escapes values for you of course and if you need to debug dump $this->db->last_query();

HiveQL : use SELECT in clause WHERE

Is there a way to do this in HiveQL :
SELECT ......
from
default.thm_renta_produits_jour rpj
WHERE
rpj.co_societe = '${hiveconf:in_co_societe}'
AND rpj.dt_jour >= (SELECT MIN(dt_jour) FROM default.calendrier WHERE co_an_semaine = '${hiveconf:in_co_an_sem}')
Because when i do this, i get this error :
FAILED: ParseException line 51:26 cannot recognize input near 'SELECT' 'MIN' '(' in expression specification
Thanks,
Hive does not support sub queries in where clause it supports sub queries in from clause only.
Hive does not support sub queries in the WHERE clause. Perhaps you can work around this by moving your sub query to a JOIN clause like so:
SELECT
rpj.*
FROM
default.thm_renta_produits_jour rpj
JOIN
( SELECT MIN(dt_jour) AS min_dt_jour
FROM default.calendrier
WHERE co_an_semaine = '${hiveconf:in_co_an_sem}'
) m
WHERE
rpj.co_societe = '${hiveconf:in_co_societe}'
AND rpj.dt_jour >= m.min_dt_jour;
Hope that helps.
I know that this is an old post, but the previous answers are now outdated. Newer versions of Hive (0.13+) support subqueries of where clauses, so your query should run.
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries#LanguageManualSubQueries-SubqueriesintheWHEREClause

Converting SQL script to LINQ with IN clause

I am trying to work out how to covert the script below from SQL in to LINQ. Any help would be welcome.
SELECT *
FROM
[tableName]
WHERE
[MyDate] IN
(SELECT
MAX([MyDate])
FROM
[tableName]
GROUP BY
[MyID])
I can't find an equivalent for the "IN" clause section. There are existing questions on this forum but none that cover selecting a DateTime.
Thanks in advance.
You can use the ".Contains(..)" function:
e.g.
var itemQuery = from cartItems in db.SalesOrderDetails
where cartItems.SalesOrderID == 75144
select cartItems.ProductID;
var myProducts = from p in db.Products
where itemQuery.Contains(p.ProductID)
select p;
Although it looks like 2 round trips, as the LINQ only constructs the query when the IEnumerable is tripped, you should get reasonable performance.
I think Any() is what you are looking for:
var result = tableName.Where(x =>
(from t in tableName
group t by t.MyID into g
where g.Max(y => y.MyDate) == x.MyDate
select 1).Any())

Selects in Joins

I have query
UPDATE THD
SET RepostFlag = 'Y'
,RunListNoRetroPolicyPrepay = ?
,RetroObject = ?
FROM TranHead AS THD
JOIN (
SELECT CustPolicyNo AS CustPolicyNo
,MIN(PremPeriod) AS PremPeriod
FROM TranHead
WHERE RepostFlag = 'Y'
AND PayoutTypeNo = ?
GROUP BY CustPolicyNo
) AS THDToBeReposted ON THD.CustPolicyNo = THDToBeReposted.CustPolicyNo
WHERE THD.RepostFlag = 'N'
AND THD.PremPeriod > THDToBeReposted.PremPeriod
fails in H2 with following message
Table "THD" not found;
I looked at http://www.h2database.com/html/grammar.html#table_expression to see if H2 supports selects in join. It appears it does. Maybe I am missing something when looking at the grammar, but it seems to me that the query should work in H2.
Anyone see what is wrong?
Thanks.
I don't believe FROM is allowed in the UPDATE syntax.
You can't update an alias, you need to have the table name specified.
Complementary to other answers, JOIN (just as FROM) is not allowed in UPDATE for H2. It would be allowed in a sub query.
Essentially, stick to the basic syntax:
UPDATE SomeTable as SomeAlias
SET SomeField = ?
WHERE (%GoWild%)
Whether or not you need the alias is up to your where clause.
Reference: http://www.h2database.com/html/grammar.html#update