How to select Top 1 1 from table - linq-to-sql

How can I write this SQL statement in LINQ ?
Select top 1 1 from MyTable
where some condition
or something like,
Select Top 1 1 from table1 inner join table2 on x=y where condition
First()/Take() returns first record. Please let me know if these functions solves the problem and how.

How about that:
var result = context.MyTable.Select(x => 1).FirstOrDefault();
with WHERE:
var result = context.MyTable.Where(x => true).Select(x => 1).FirstOrDefault();
Just add Select(x => 1).FirstOrDefault() at the end of the LINQ query.

Related

Is there a way to make an AND operation over a column of TINYINT(1) in MYSQL?

I got the following table and I need to return 1 if all rows have disponibilidad = 1
The following QUERY works just fine, but i was looking for a more efficient way of doing it.
QUERY:
SELECT IF(AVG(disponibilidad) < 1, 0, 1) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1;
RESULT:
As I see it, with an 'AND' it would be far more efficient, since it wouldn't have to do AVG().
MySql does not support a boolean AND aggregate function like Postgresql's bool_and.
Why not a simple MIN():
SELECT MIN(disponibilidad) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1;
This will return 1 only if all values of the column are 1 (provided the column is not nullable) and 0 if there is at least one row with 0.
How about something like
SELECT IF(COUNT(*)>0,0,1) AS newResult
FROM pasteleria.compone
RIGHT JOIN pasteleria.ingredientes
ON pasteleria.compone.id_ingrediente = pasteleria.ingredientes.id_ingrediente
WHERE id_componente = 1
AND disponibilidad <> 1
so that if there are any rows where disponibilidad is not 1, you output 0, otherwise if it's zero (so all disponibilidad values are 1) you output 1?

Union of two tables in Zend 2

I want to union two tables with where clause in zf2:-
table1 app_followers
table2 app_users
where condition could be anything
and order by updated_date.
Please let me know the query for zend 2.
Thanks..
Using UNION is ZF2:
Using ZF2 dedicated class Combine Zend\Db\Sql\Combine
new Combine(
[
$select1,
$select2,
$select3,
...
]
)
A detailed example which uses combine is as follows:
$select1 = $sql->select('java');
$select2 = $sql->select('dotnet');
$select1->combine($select2);
$select3 = $sql->select('android');
$selectall3 = $sql->select();
$selectall3->from(array('sel1and2' => $select1));
$selectall3->combine($select3);
$select4 = $sql->select('network');
$selectall4 = $sql->select();
$selectall4->from(array('sel1and2and3' => $selectall3));
$selectall4->combine($select4);
$select5 = $sql->select('dmining');
$selectall5 = $sql->select();
$selectall5->from(array('sel1and2and3and4' => $selectall4));
$selectall5->combine($select5);
which is equivalent to the normal SQL query for UNION:
SELECT * FROM java
UNION SELECT * from dotnet
UNION SELECT * from android
UNION SELECT * from network;
UNION SELECT * from dmining;
I hope it helps.
I wanted to do a similar task and spent a lot of time while to figure out how to do that in the right way.
The idea with Laminas\Db\Sql\Combine is really well but you cannot apply the ordering to this object and as the result, it's useless in this case.
Finally, I ended up with the next code:
$skill = $sql->select('skill');
$language = $sql->select('language');
$location = $sql->select('location');
$occupation = $sql->select('occupation');
$skill->combine($language);
$language->combine($location);
$location->combine($occupation);
$combined = (new Laminas\Db\Sql\Select())
->from(['sub' => $skill])
->order(['updated_date ASC']);
However, it's a bit messy with parentheses. If it's a matter for you, please check this comment on Github, but on MySQL id doesn't matter, not sure about other databases.

Laravel 4 - SQL query to Laravel Eloquent query

I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();

LINQ TO SQL: HAVING COUNT(table_id) < 2

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 );

LINQ query help needed for Intersect

LINQ gurus, I am looking for help to write a query...
I have a table with Person records, and it has a nullable ParentID column, so it is kind of self-referencing, where each record might have a Parent.
I am looking for unprocessed rows whose parent rows were processed.
This SQL works fine:
SELECT *
FROM Person
where IsProcessed = 0 and
ParentId in
(
select Id from Person
where IsProcessed = 1
)
I tried a number of LINQ queries, but they failed. Now, I'm trying:
var qParent =
from parent in db.Person
where
parent.IsProcessed == true
select parent.ID;
var qChildren = from child in db.Person
where
child.IsProcessed == false
&& child.ParentId.HasValue
select child.ParentId.Value;
var q2 = qChildren.Intersect(qParent);
This yields SQL with a DISTINCT clause, for some reason, and I am baffled why DISTINCT is generated.
My main question is how to write LINQ for the SQL statement above?
Thanks in advance.
Intersect is a set operation - it is meant to return a set of distinct elements from the intersection. It seems reasonable to me that it would use DISTINCT in the SQL. There could be multiple children with the same parent, for example - Intersect should only return that ID once.
Is there any reason you don't want to use a join here?
var query = from parent in db.Person
where parent.IsProcessed
join child in db.Person.Where(child => !child.IsProcessed)
on parent.ID equals child.ParentId.Value
select child;
The query can be translated literally into :
var parentIds = db.Person.Where(x => x.IsProcessed)
.Select(x => x.Id)
.ToList();
var result = db.Person.Where(x => !x.IsProcessed && parentIds.Contains(x => x.Id))
.ToList();