How to 'order by' a variable in Python and SQL? - sqlite

I've had a look at this solution here. But I don't quite fully understand what is going on, hence I don't know how to use a similar technique in my code.
order = "Movies.Rating_IMDB ASC"
general = db.execute (
"""
SELECT Movies.Movie_ID, Movies.Name, Movies.Year, Movies.Image
FROM Movie_Genre
JOIN Movies ON Movie_Genre.Movie_ID = Movies.Movie_ID
JOIN Genres ON Movie_Genre.Genre_ID = Genres.Genre_ID
WHERE Genres.Genre = ?
ORDER BY ?;
""",
(str(selectedGenre), order,)
)
basic = general.fetchall()

Related

Complex AX Query

i want to rebuild this SQL Query as AX Query.
I tried it in several ways, but I don't get it.
I am not completely new to AX queries, but I only have experience with some simple queries not with such complex SQL queries.
SELECT * FROM ( SELECT DH.[RECID] AS RECID_DIMENSIONHIERARCHY
,DH.[NAME] AS NAME__DIMENSIONHIERARCHY
,DH.[DESCRIPTION] AS DESC__DIMENSIONHIERARCHY
,DH.[PARTITION] AS PARTITION_DIMENSIONHIERARCHY
,DL.[DIMENSIONATTRIBUTE] AS RECID_DIMENSIONATTRIBUTE
,DA.[NAME] AS NAME_DIMENSIONATTRIBUTE
,DN.[RECID] AS RECID_DIMENSIONCONSTRAINTNODE
,DNC.[RECID] AS RECID_DIMENSIONCONSTRAINTNODECRITERIA
,DNC.[RANGETO] AS #Owner
,DNCR.[WILDCARDSTRING] AS #Agreement
FROM (SELECT * FROM [dbo].[DIMENSIONHIERARCHY]
WHERE [STRUCTURETYPE] = 1 AND [NAME] LIKE 'AG-OW%'
) AS DH
INNER JOIN [dbo].[DIMENSIONHIERARCHYLEVEL] AS DL
ON DH.[RECID] = DL.[DIMENSIONHIERARCHY]
AND DH.[PARTITION] = DL.[PARTITION]
INNER JOIN [dbo].[DIMENSIONATTRIBUTE] AS DA
ON DL.[DIMENSIONATTRIBUTE] = DA.[RECID]
AND DL.[PARTITION] = DA.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODE] AS DN
ON DL.[RECID] = DN.[DIMENSIONHIERARCHYLEVEL]
AND DL.[PARTITION] = DN.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODECRITERIA] AS DNC
ON DN.[RECID] = DNC.[DIMENSIONCONSTRAINTNODE]
AND DN.[PARTITION] = DNC.[PARTITION]
INNER JOIN [dbo].[DIMENSIONCONSTRAINTNODECRITERIA] AS DNCR
ON DN.[PARENTCONSTRAINTNODE] = DNCR.[DIMENSIONCONSTRAINTNODE]
AND DN.[PARTITION] = DNCR.[PARTITION]
) AS Sub
You need to break down your query and implement it in small chunks. Then combine all of it to get the desired result.
There are two ways to create query in X++.
Create query using select statement for example:
Select * from HcmWorker join * from DirPerson
where DirPerson.RecId == HcmWorker.Person
See this link : Select statement syntax
Create query with AOT structure. You might want to have a look at the following link:
Create query in AOT by using X++

How to make JOIN with OR expression in DQL?

Here is the SQL equivalent of what I expect to get from Doctrine:
SELECT c.* FROM comments c
LEFT JOIN articles a
ON a.id = c.articles_id OR a.translation = c.articles_id
WHERE c.published = 1 AND c.language = a.language
The problem is that I cannot make Doctrine to generate the JOIN operation with OR as it is supposed to be. If we execute query from the following QueryBuilder object:
$qb->select('c')
->from('Project:Comment', 'c')
->leftJoin('c.article', 'a', 'WITH', 'a = c.article OR a.translation = c.article')
->where('c.published = true AND c.language = a.language');
we receive the following SQL statement:
SELECT
...
FROM comments c0_
LEFT JOIN articles a0_ ON c0_.articles_id = a0_.id
AND (
a0_.id = c0_.articles_id OR
a0_.translation = c0_.profiles_id
)
WHERE c0_.published = 1 AND c0_.language = a0_.language
which is obviously not the same as the initial query, as WITH operator seems to add additional conditions to the basic one instead of replacing the whole condition.
Is there any way to force Doctrine to output exactly what I need? I know that I may use native SQL but I doubt that it will be as convenient as QueryBuilder. Maybe there is a way to extend Doctrine with normal JOIN ON implementation instead of this odd JOIN WITH?
Doctrine doesn't implement this because it is (as far as I understand at least) not considered optimized enough for SQL.
See this SO post for precisions.
What you intend to do could appearantly be done using Union and other types of Join.

Where-Condition as IN(Subquery) with Doctrine2 in Symfony2.3.1 doesnt work

---- Done with Symfony2.3.1 and Doctrine2 ----
Sorry, i hope i was not too stupid to find a suitable solution for my problem. I try to build a Query for hours.
SELECT * FROM product
WHERE product_id in
(
SELECT product_id from (
SELECT count(*) as result_amount, product_id FROM product_x_attribut
JOIN productattribut on productattribut_id = productattribut.id
WHERE (
productkey = "price" and
stringType = "premium"
) or (
productkey = "size" and
stringType = "S"
)
GROUP BY product_id
HAVING result_amount = 2
) as temp
)
GROUP BY product_id
ORDER BY p0_.name ASC
This is the SQL which works fine in phpmyAdmin.
This can be seen like
Select * from abc where abc.x in ( Select * from ( select * from ) as abcd )
So there is one core query, i call it subSubQuery, the second query around the core will be called subQuery and the outer Query is just the outer Query, no a Subquery.
I could build the subSubQuery with Doctrine2.
But i cannot built the subQuery like this
Select product_id from ( $subSubQuery->getQuery()->getDQL() )
I want to do the subQuery like this
$subQuery = $repositoryProduct->createQueryBuilder('product');
$subQuery->add('select', 'product_id');
$subQuery->add('from',$subSubQuery->getDQL() );
// However to set an alias is a miracle for me, this didnt work off course
$subQuery->add('as','tmp' );
This is the subQuery.
I also cannot build the outer Query
Select * from abc where abc.x in ( $subQuery->getQuery()->getDQL() )
I want to do this like this
$query->where(
$query->expr()->in('product.id', $subQuery->getDQL() )
);
But i try to build this with Doctrine2 like this:
I am so down, i tried ->getSQL(), ->getDQL(), i tried as much as i was able to detect as a suitable tiny step to a solution for this problem and i has tried as much keyword in google as my finger were able to write... I hope someone could help me to find a solution...
Thanks a lot to each helpful advise.
I know that statements like this work:
$qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL()));
Your question is kind of hard to follow. Consider using pastebin to show all your mappings as they currently exist. And then maybe presenting a simplieid query?
My $qbGameId query was built with:
$qbGameId = $em->createQueryBuilder();
$qbGameId->addSelect('distinct gameGameId.id');
$qbGameId->from('ZaysoCoreBundle:Event','gameGameId');
// Assorted joins and where conditions

Getting the last item from a Drupal db_fetch_object

What's the best way to do this? I've been falling back onto doing a while() loop over the result and snagging the last one as it goes by, but this seems a little, um, inelegant. D7 offers some help here, but is there any advice out there for D6? Thanks!
Why not reverse the order of your query and limit to 1 and get that?
Something like:
$result = db_query_range("SELECT * FROM {table} ORDER BY field DESC", 0, 1);
http://api.drupal.org/api/drupal/includes--database.mysql.inc/function/db_query_range/6
In general case (no engine tips like for mysql), use:
$query = 'SELECT nid, title from {node} WHERE type="page"';
$query_count = 'SELECT count(*) from {node} WHERE type="page"';
$count = db_result(db_query($query_count)); // $query_count
$last_record = db_fetch_object(db_query_range($query, $count-1, 1));
If query use ordering, just use "counter-ordering":
$query = 'SELECT nid, title from {node} WHERE type="page" ORDER BY nid ASC';
// ...
$counterquery = 'SELECT nid, title from {node} WHERE type="page" ORDER BY nid DESC LIMIT 0,1';
$last_record = db_fetch_object(db_query($counterquery));
Try to use db_last_insert_id()

Magento: Filtering a Collection with grouped Clauses

I would like to filter a collection with grouped clauses. In SQL this would look something like:
SELECT * FROM `my_table` WHERE col1='x' AND (col2='y' OR col3='z')
How can I "translate" this to filtering a collection with ->addFieldToFilter(...)?
Thanks!
If your collection is an EAV type then this works well:
$collection = Mage::getResourceModel('yourmodule/model_collection')
->addAttributeToFilter('col1', 'x')
->addAttributeToFilter(array(
array('attribute'=>'col2', 'eq'=>'y'),
array('attribute'=>'col3', 'eq'=>'z'),
));
However if you're stuck with a flat table I don't think addFieldToFilter works in quite the same way. One alternative is to use the select object directly.
$collection = Mage::getResourceModel('yourmodule/model_collection')
->addFieldToFilter('col1', 'x');
$collection->getSelect()
->where('col2 = ?', 'y')
->orWhere('col3 = ?', 'z');
But the failing of this is the order of operators. You willl get a query like SELECT * FROM my_table WHERE (col1='x') AND (col2='y') OR (col3='z'). The OR doesn't take precedence here, to get around it means being more specific...
$collection = Mage::getResourceModel('yourmodule/model_collection')
->addFieldToFilter('col1', 'x');
$select = $collection->getSelect();
$adapter = $select->getAdapter();
$select->where(sprintf('(col2 = %s) OR (col3 = %s)', $adapter->quote('x'), $adapter->quote('y')));
It is unsafe to pass values unquoted, here the adapter is being used to safely quote them.
Finally, if col2 and col3 are actually the same, if you're OR-ing for values within a single column, then you can use this shorthand:
$collection = Mage::getResourceModel('yourmodule/model_collection')
->addFieldToFilter('col1', 'x')
->addFieldToFilter('col2', 'in'=>array('y', 'z'));

Resources