How could I translate this:
SELECT id,
FROM user
WHERE NOT EXISTS (SELECT *
FROM user_agency_assoc
WHERE user.ID = user_agency_assoc.user_id)
AND user.invited_by IS NOT NULL
as an SQLAlchemy ORM query?
You could do something like this,
db.session.query(user.id)
.filter(
~user_agency_assoc.query
.filter(user.id == user_agency_assoc.user_id)
.exists()
)
assuming your corresponding model names are user and user_agency_assoc
Related
I'm trying to create a custom query with BigQuery in Google
I can do almost everything using SQLAlchemy filter function
query = TestModel.query.filter(TestModel.timestamp.__gt__(1010101010))
But I want to add custom filter on where clause like below
AND EXISTS (SELECT * FROM UNNEST(column_name) WHERE column_key LIKE '%tit%')
Is there a way to append filter using string like above?
Raw query
You can clearly do this like below:
text_clause = text("EXISTS (SELECT * FROM UNNEST(column_name) WHERE column_key LIKE '%tit%')")
ts = 1010101010
q = (
session.query(TestModel)
.filter(TestModel.timestamp > ts)
.filter(text_clause)
)
But it is going to be cleaner and more maintainable to avoid it if you can.
ORM Query
Below should give you an idea on how to implement it:
ts = 1010101010
subq = (
select(literal("*"))
.select_from(func.unnest(TestModel.column_name))
.filter(TestModel.column_key.contains("tit"))
).exists()
q = (
session.query(TestModel)
.filter(TestModel.timestamp > ts)
.filter(subq)
)
I need to have an oridinal number from mysql database. I found how emulate of row_num in mysql like this:
SET #row=0;
SELECT * FROM (
SELECT (#row:=#row+1) AS no, id, name FROM `attribute` ORDER BY id
) t WHERE name LIKE "%Jo%"
I begin code with:
$this->getEntityManager()->getConnection()->exec("SET #counter = 0");
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->where($expr->in('att.ordinal_number', $this->createQueryBuilder('att')->
select('(#counter:=#counter+1) AS ordinal_number')->
from(\App\Entity\Attribute::class, 'att')->
orderBy('att.id')->getDQL()))
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->addSelect('(SELECT (#counter:=#counter+1) AS oridinal_number, id, '
.' name FROM App:Entity:Atrribute ORDER BY id)')
Above give me:
Error: Expected Literal, got '#'
Anybody know how to emulate row_number in doctrine with mysql?
Thanks in advance.
AFAIK there is no direct way to incorporate these DB variables in DQL or query builder, you will need to execute Native SQL and then use ResultSetMapping class to map the result of query to your entity
SQL
SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM `attribute` ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE "%Jo%"
Resultset Mapping
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Attribute', 'a');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'name', 'name');
$rsm->addScalarResult('no', 'no');
$query = $this->_em->createNativeQuery('SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM attribute ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE ?',$rsm);
$query->setParameter(1, '%Jo%');
$users = $query->getResult();
I have the following query:
select coalesce(round(sum(vdamesatual) /
(select count(*)
from feriados
where month(data)=month(current_date) and
day(data)<day(current_date) and
diadasemana in(2,3,4,5,6) and
feriadonacional=0 and
uf <> (select distinct uforigem from baseprodutos where Empresa = 'test'))
*
(select count(*)
from feriados
where month(data)=month(current_date) and
day(data)>=day(current_date) and
diadasemana in(2,3,4,5,6) and
feriadonacional=0 and
uf <> (select distinct uforigem from baseprodutos where Empresa = 'test'))),0) as projecao
from baseprodutos
where Empresa = 'test' and
UFDest = 'uf' and
Fabricante = 'sample';
As you can see I have a coalesce right after the first select, and I am having trouble finding the right way to write this with sequelize; Would you have some suggestion?
I don't really follow the logic of your query, but the rule in Sequelize is that you can call any function with sequelize.fn() so a simple example of using COALESCE in Sequelize to get a value from 2 columns with an alias would be like this in your attributes:
[[sequelize.fn('COALESCE', mysql.col('col_name'), mysql.col('col_2_name')), 'alias'], 'another_col']
You can include another function if needed, like SUM by doing like this:
[[sequelize.fn('COALESCE', sequelize.fn('SUM', (mysql.col('col_name'), mysql.col('col_2_name'))), (some other code here ...)),'alias']]
I'm new to MySQL and I'm trying to make the following pseudocode work:
SELECT IF(
EXISTS(SELECT * FROM users WHERE `email`="admin" AND `token`="blablabla"),
(UPDATE * FROM sometable WHERE `var`="notimportant"),
"NOT_AUTHORIZED");
What I'm trying to achieve is running code based on the presence of a row, and if it doesn't exists return a message, or something usable. If it does exists, run another SQL command instead, and return those results.
Is this possible?
Your intent is a bit hard to follow from the invalid syntax. But the gist of your question is that you can use a where clause:
UPDATE sometable
SET . . .
WHERE var = 'notimportant' AND
EXISTS (SELECT 1 FROM users WHERE email = 'admin' AND token = 'blablabla');
You can also represent this as a JOIN. Assuming the subquery returns at most one row:
UPDATE sometable t CROSS JOIN
(SELECT 1
FROM users
WHERE email = 'admin' AND token = 'blablabla'
LIMIT 1
) x
SET . . .
WHERE var = 'notimportant' ;
I'm building a website for an school and i need a list of users that don't have 2 parents asigned. This would be the SQL query:
SQL
SELECT * FROM users
WHERE user_rol = 4
AND user_id IN
(SELECT parent_user_id FROM user_parents
GROUP BY parent_user_id
HAVING COUNT(parent_user_id) < 2);
I'm trying to use LINQ for the same query but I don't know how to use HAVING with LINQ. This has been my closer try for the moment.
SUB-QUERY FOR IN
List<long> usersWithTwoParentsIds = (from currentStudents in contexto.user_parents
select currentStudents.parent_user_id).ToList<long>();
--HELP! having count(currentStudents.parent_user_id) < 2
QUERY
List<vw_user> userList = (from currentStudents in contexto.vw_user
where !usersWithTwoParentsIds.Contains(currentStudents.user_id)
&& currentStudents.group_id == groupID select currentStudents).ToList<vw_user>()
Can anybody give a clue? Thanks :)
Something like this:
var usersWithTwoParentsIds = (
from userParent in contexto.user_parents
group userParent by userParent.parent_user_id into userParentGroups
where userParentGroups.Count() < 2
select userParentGroups.Key)
.ToList();
Assuming the key relations are proper in your data context:
var dat = Context.Users.Where( u => u.Parents.Count() < 2 );