I have this query:
String queryStr = 'SELECT COUNT(*) FROM tester x WHERE x.state !=:state'
setParameter("state", "state1");
I want to count all that are "state1" and "state2"
Is there a way to do it rather than :
String queryStr = 'SELECT COUNT(*) FROM tester x WHERE (x.state !=:state1 AND x.state !=:state2)';
setParameter("state1", "state1");
setParameter("state2", "state2");
Thanks
use not in
WHERE (x.state NOt IN (:state1,:state2))
then your whole query will be
'SELECT COUNT(*) FROM tester x WHERE (x.state NOt IN (:state1,:state2))';
Note: above solution is according to yor query, but according to your text [I want to count all that are "state1" and "state2"]
then your query can be
'SELECT COUNT(*) FROM tester x WHERE x.state = :state1 AND x.state = :state2';
Related
I'm trying to do next query to the DB to get the next results:
Expected results
I have the table Areas, but I want to sort the results according to the responsible, it means, the responsibles with more areas at the top and the responsibles with less areas at the bottom.
Actually I'm doing it with the next Mysql Query which works perfectly:
SELECT a.id_Area,
a.name,
a.responsible
FROM FSA_Areas a
WHERE enabled=TRUE
AND id_Plant = 1
ORDER BY (SELECT COUNT(*)
FROM FSA_Areas a1
WHERE a1.Responsible = a.Responsible
AND a1.id_Plant = a.id_Plant
AND Enabled='1') DESC,
a.responsible;
But now I want to do it in Doctrine Query Builder or DQL
I've tried this, It didt not work:
$query = $em->createQueryBuilder()
->select('u')
->from('FSABundle:FSAArea','u')
->orderBy($this->createQueryBuilder('u1')
->select('count(u1)')
->from('FSABundle:FSAArea', 'u1')
->where('u1.responsible = u.responsible')
->andWhere('u1.plant = u.plant')
->andWhere('u1.enabled = enabled')
,'DESC')
->getQuery()->getResult();
return $query;
Any Idea about how to the same Mysql Query into DQL or Query Builder?
TEST 1:
$sub = $em->createQueryBuilder('a')
->select('COUNT(a.id)')
->from('FSABundle:FSAArea','a')
->where('a.responsible = u.responsible')
->andWhere('a.plant = u.plant')
->andWhere('a.enabled = :status')
->setParameter('status','true');
$qb->select('u')
->from('FSABundle:FSAArea','u')
->where('u.enabled = :status')
->andWhere('u.plant = :idPlant')
->setParameter('status','enabled')
->setParameter('idPlant','1')
->orderBy($sub->getDQL(),'DESC');
return $qb->getQuery()->getResult();
My Query looks like
$search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd
LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid
LEFT JOIN users ON nd.uid = users.uid
WHERE nd.status = 1 AND nd_rev.body LIKE LOWER('%node/100%')
AND nd.nid NOT IN(SELECT DISTINCT nid FROM term_node WHERE tid = 293)");
This query actually returns all the matches from node_revisions.body field, Which includes
node/1000, node/1001.... Etc.,
I want to get only the result of exact match where possible like
"node/100"
"node/100/"
"/node/100"
"/node/100/"
'node/100'
'node/100/'
'/node/100'
'/node/100/'
and not like
"node/1006"
"node/10064/"
"/node/1000"
"/node/10001/"
'node/10023'
'node/1005/'
'/node/1001'
'/node/10069/'
This above query returned me result which has string like below..
..a href="/node/1006"
How to avoid this kind of errors? Please help..
Try removing the % after 100 so the search won't consider any digit after 100, like this:
LOWER('%node/100')
Then consider the following Regular Expression
Example:
`nd_rev.body` REGEXP "^/?node/100/?$"
Oh ya... I got an resolution for this.. I redefined my query like below and it gives me result as expected..
$search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd
LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid
LEFT JOIN users ON nd.uid = users.uid
WHERE nd.status = 1 AND nd_rev.body RLIKE '[[:<:]]" . $search_string . "[[:>:]]'
AND nd.nid NOT IN(SELECT DISTINCT nid FROM term_node WHERE tid = 293)");
Look at
nd_rev.body RLIKE '[[:<:]]" . $search_string . "[[:>:]]'
This is what i expected
I'm trying to run a special SQL query in ZF 2.
SELECT listingId, COUNT(*) as num
FROM
(SELECT DISTINCT listingId, locationId
FROM l_f_locations
WHERE locationId IN ( 7, 9, 10)) AS foo
GROUP by listingId, HAVING num = 3
I tried creating the subquery first as it's a complete MySQL query but then fail to integrate it into the main query at all. I can't alias the subquery e.g. "AS foo" as this is a requirement for the complete SQL squery to work.
Any ideas?
First of all, you can do this without a sub-query:
SELECT listingId, COUNT(DISTINCT locationId) AS num
FROM l_f_locations
WHERE listingId IN(7,9,10)
GROUP BY listingId
HAVING num = 3;
For future reference, however, you could do the query you mention using a pair of Zend_Db_Select objects, one for the sub-query and another for the main:
$subQuery = $dbAdapter->select()
->from('l_f_locations', array('listingId', 'locationId'))
->where('locationId IN(7,9,10)')
->group('listingId')
->group('locationId');
$select = $dbAdapter->select()
->from($subQuery, array('*', 'num' => 'COUNT(*)'))
->group('listingId')
->having('num = 3');
$result = $select->query()->fetchAll();
code = 00000000005555
2nd option code = 00000000000555
hi i am try to find out same function like ltrim() of php
SELECT * FROM db1.stock JOIN db2.prodinfo ON replace(db2.prodinfo.code,0000000000,'') = replace(db1.stock.code,0000000000,'') WHERE db1.stock.InvNo ='12' and db2.prodinfo.Cat = 'super'
i rum this temporary. becuse zero might be increase and decrease i
example above. i am just want to remove zero in this query
thanks
try by casting it into numeric,
SELECT *
FROM db1.stock JOIN db2.prodinfo ON
CAST(db2.prodinfo.code AS SIGNED) = CAST(db1.stock.code AS SIGNED)
WHERE db1.stock.InvNo ='12' and db2.prodinfo.Cat = 'super'
or
SELECT *
FROM db1.stock JOIN db2.prodinfo ON
CAST(db2.prodinfo.code AS DECIMAL(15,0)) = CAST(db1.stock.code AS AS DECIMAL(15,0))
WHERE db1.stock.InvNo ='12' and db2.prodinfo.Cat = 'super'
How do I do this
Select top 10 Foo from MyTable
in Linq to SQL?
Use the Take method:
var foo = (from t in MyTable
select t.Foo).Take(10);
In VB LINQ has a take expression:
Dim foo = From t in MyTable _
Take 10 _
Select t.Foo
From the documentation:
Take<TSource> enumerates source and yields elements until count elements have been yielded or source contains no more elements. If count exceeds the number of elements in source, all elements of source are returned.
In VB:
from m in MyTable
take 10
select m.Foo
This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.
It also assumes that Foo is a column in MyTable that gets mapped to a property name.
See http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx for more detail.
Use the Take(int n) method:
var q = query.Take(10);
The OP actually mentioned offset as well, so for ex. if you'd like to get the items from 30 to 60, you would do:
var foo = (From t In MyTable
Select t.Foo).Skip(30).Take(30);
Use the "Skip" method for offset.
Use the "Take" method for limit.
#Janei: my first comment here is about your sample ;)
I think if you do like this, you want to take 4, then applying the sort on these 4.
var dados = from d in dc.tbl_News.Take(4)
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
};
Different than sorting whole tbl_News by idNews descending and then taking 4
var dados = (from d in dc.tbl_News
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
}).Take(4);
no ? results may be different.
This works well in C#
var q = from m in MyTable.Take(10)
select m.Foo
Whether the take happens on the client or in the db depends on where you apply the take operator. If you apply it before you enumerate the query (i.e. before you use it in a foreach or convert it to a collection) the take will result in the "top n" SQL operator being sent to the db. You can see this if you run SQL profiler. If you apply the take after enumerating the query it will happen on the client, as LINQ will have had to retrieve the data from the database for you to enumerate through it
I do like this:
var dados = from d in dc.tbl_News.Take(4)
orderby d.idNews descending
select new
{
d.idNews,
d.titleNews,
d.textNews,
d.dateNews,
d.imgNewsThumb
};
You would use the Take(N) method.
Taking data of DataBase without sorting is the same as random take
Array oList = ((from m in dc.Reviews
join n in dc.Users on m.authorID equals n.userID
orderby m.createdDate descending
where m.foodID == _id
select new
{
authorID = m.authorID,
createdDate = m.createdDate,
review = m.review1,
author = n.username,
profileImgUrl = n.profileImgUrl
}).Take(2)).ToArray();
I had to use Take(n) method, then transform to list, Worked like a charm:
var listTest = (from x in table1
join y in table2
on x.field1 equals y.field1
orderby x.id descending
select new tempList()
{
field1 = y.field1,
active = x.active
}).Take(10).ToList();
This way it worked for me:
var noticias = from n in db.Noticias.Take(6)
where n.Atv == 1
orderby n.DatHorLan descending
select n;