Get data from another column where first column id is equals other and other column equals X - sql

My problem is:
I would like to get all advertistments where id of Description column is equals with Advertistment's column.
Let's say that Advertistment column is connected with Description column.
I would like to gain all description's id where one of its column called type_of_house is equals m.
Then show all advertistment where advertistment's id is equals with description's id.
In short way: advertistment shows info about houses, descriptions store houses type D and M and I want show all advertistments with houses type of M.
This is correct sql:
SELECT * FROM advertistment, description WHERE advertistment.id_advertistment = description.id_description AND description.type_of_house = "m"
I have no idea how write it into zend. I tried something like that. This function I wrote in model folder.
public function takeAll() {
$select = $this->_db->select();
$select->from(array('a' => 'advertistment', 'd' => 'description'));
$select->where('a.id_advertistment = d.id_description AND d.type_of_house = m');
return $select->query()->fetchAll();
}

You're actually quite close. This should work:
public function takeAll() {
$select = $this->_db->select();
$select->from(array('a' => 'advertistment'));
$select->join(array('d' => 'description'), 'a.id_advertistment = d.id_description');
$select->where('d.type_of_house = ?', 'm');
return $this->_db->fetchAll($select);
}

Related

Linq2DB can't translate a mapped column in Where clause

I'm working with a legacy Oracle database that has a column on a table which stores boolean values as 'Y' or 'N' characters.
I have mapped/converted this column out like so:
MappingSchema.Default.SetConverter<char, bool>(ConvertToBoolean);
MappingSchema.Default.SetConverter<bool, char>(ConvertToChar);
ConvertToBoolean & ConvertToChar are simply functions that map between the types.
Here's the field:
private char hasDog;
[Column("HAS_DOG")]
public bool HasDog
{
get => ConvertToBoolean(hasDog);
set => hasDog = ConvertToChar(value);
}
This has worked well for simply retrieving data, however, it seems the translation of the following:
var humanQuery = (from human in database.Humans
join vetVisit in database.VetVisits on human.Identifier equals vetVisit.Identifier
select new HumanModel(
human.Identifier
human.Name,
human.HasDog,
vetVisit.Date,
vetVisit.Year,
vetVisit.PaymentDue
));
// humanQuery is filtered by year here
var query = from vetVisits in database.VetVisits
select new VetPaymentModel(
(humanQuery).First().Year,
(humanQuery).Where(q => q.HasDog).Sum(q => q.PaymentDue), -- These 2 lines aren't correctly translated to Y/N
(humanQuery).Where(q => !q.HasDog).Sum(q => q.PaymentDue)
);
As pointed out above, the .Where clause here doesn't translate the boolean comparison of HasDog being true/false to the relevant Y/N values, but instead a 0/1 and results in the error
ORA-01722: invalid number
Is there any way to handle this case? I'd like the generated SQL to check that HAS_DOG = 'Y' for instance with the specified Where clause :)
Notes
I'm not using EntityFramework here, the application module that this query exists in doesn't use EF/EFCore
You can define new mapping schema for your particular DataConnection:
var ms = new MappingSchema();
builder = ms.GetFluentMappingBuilder();
builder.Entity<Human>()
.Property(e => e.HasDog)
.HasConversion(v => v ? 'Y' : 'N', p => p == 'Y');
Create this schema ONCE and use when creating DataConnection

The nested query does not have the appropriate keys

Firstly I have a function which takes 2 parameters( longitude, latitude).
RETURNS TABLE
AS
RETURN
(
select dbo.GeoCalculateDistance (#lat1Degrees,#lon1Degrees,Latitude,Longitude) as Distance, PKRestaurantId as PkKeyId from StRestaurant
)
And as you realise, I have a table that called StRestaurant. In this table I have 4 columns(PkRestaurantId, RegionId , Longitude, Latitude).
And, I need a method that takes 4 parameters.
public List<RestaurantDetailDto> GetRestaurant(int regionid, decimal latitude, decimal longitude, OrderType orderType)
{}
This method will give the restauants around me. But if I want to systematize this list with distance, I must join my Restaurant table and the function. Here is my query.
var query = from restaurant in context.StRestaurant
join distance in context.CalculateDistanceTable(latitude, longitude) on restaurant.PKRestaurantId equals distance.PkKeyId
where restaurant.FKRegionId == regionid
select new
{
Restaurant = restaurant,
DistanceTable = distance,
};
And then I am checking the orderType,
switch (orderType)
{
case OrderType.Distance:
query = query.OrderBy(x => x.DistanceTable.Distance);
break;
// and the anothers
}
Lastly, I am trying to take this list as;
var queryResult = query.ToList();
All the time I took this error :
The nested query does not have the appropriate keys.
I also try the above query but it return with the same error :s
var query = context.StRestaurant.Where(x => x.FKRegionId == regionid && x.IsActive).Join(
context.CalculateDistanceTable(latitude, longitude),
restaurant => restaurant.PKRestaurantId,
result => result.PkKeyId,
(restaurant, result) => new
{
Restaurant = restaurant,
MinumumPackagePrice = restaurant.StRestaurantRegionRelation.FirstOrDefault(x => x.FKRestaurantId == restaurant.PKRestaurantId).MinumumPackageCharge,
DistanceTable = result,
RestaurantImage = restaurant.StRestaurantImage.Where(x => x.IsDefault && x.FKRestaurantId == restaurant.PKRestaurantId),
}
);
Please help!!
I've seen this before when doing an .Include() on the result. I imagine your projection (in the second example) might be doing this internally. Could you add this to the first part?
In this case, I've had to add the .Include() on the source table:
from a in context.A.Include("relationship")
join b in context.MyFunction(...)
...
There are a some things that you can try here. First, rewrite your SQL function so that it has a primary key:
CREATE FUNCTION CalculateDistanceTable
(
-- Add the parameters for the function here
#lat1Degrees float,
#lon1Degrees float
)
RETURNS
#RestaurantDistances TABLE
(
-- Add the column definitions for the TABLE variable here
PkKeyId int NOT NULL primary key,
Distance float NOT NULL
)
AS
BEGIN
INSERT INTO #RestaurantDistances
SELECT dbo.GeoCalculateDistance(#lat1Degrees, #lon1Degrees, Latitude, Longitude) AS Distance, PKRestaurantId AS PkKeyId
FROM StRestaurant
RETURN
END
GO
Also, you can try changing your LINQ join to use anonymous types to perform the join.
var query = from restaurant in context.StRestaurant
join distance in context.CalculateDistanceTable(latitude, longitude) on new { Key = restaurant.PKRestaurantId } equals new { Key = distance.PkKeyId }
where restaurant.FKRegionId == regionid
select new
{
Restaurant = restaurant,
DistanceTable = distance,
};
If neither one of these helps let me know and I'll try to update this answer as appropriate.

Group By Sum Linq to SQL in C#

Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don't understand enough to apply other solutions to my own.
I have a view in my database called view_ProjectTimeSummary, this has the following fields:
string_UserDescription
string_ProjectDescription
datetime_Date
double_Hours
I have a method which accepts a to and from date parameter and first creates this List<>:
List<view_UserTimeSummary> view_UserTimeSummaryToReturn =
(from linqtable_UserTimeSummaryView
in datacontext_UserTimeSummary.GetTable<view_UserTimeSummary>()
where linqtable_UserTimeSummaryView.datetime_Week <= datetime_To
&& linqtable_UserTimeSummaryView.datetime_Week >= datetime_From
select linqtable_UserTimeSummaryView).ToList<view_UserTimeSummary>();
Before returning the List (to be used as a datasource for a datagridview) I filter the string_UserDescription field using a parameter of the same name:
if (string_UserDescription != "")
{
view_UserTimeSummaryToReturn =
(from c in view_UserTimeSummaryToReturn
where c.string_UserDescription == string_UserDescription
select c).ToList<view_UserTimeSummary>();
}
return view_UserTimeSummaryToReturn;
How do I manipulate the resulting List<> to show the sum of the field double_Hours for that user and project between the to and from date parameters (and not separate entries for each date)?
e.g. a List<> with the following fields:
string_UserDescription
string_ProjectDescription
double_SumOfHoursBetweenToAndFromDate
Am I right that this would mean I would have to return a different type of List<> (since it has less fields than the view_UserTimeSummary)?
I have read that to get the sum it's something like 'group / by / into b' but don't understand how this syntax works from looking at other solutions... Can someone please help me?
Thanks
Steve
Start out by defining a class to hold the result:
public class GroupedRow
{
public string UserDescription {get;set;}
public string ProjectDescription {get;set;}
public double SumOfHoursBetweenToAndFromDate {get;set;}
}
Since you've already applied filtering, the only thing left to do is group.
List<GroupedRow> result =
(
from row in source
group row by new { row.UserDescription, row.ProjectDescription } into g
select new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
}
).ToList();
(or the other syntax)
List<GroupedRow> result = source
.GroupBy(row => new {row.UserDescription, row.ProjectDescription })
.Select(g => new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
})
.ToList();

Linq query using list output as input

I am using Linqpad and have odata connection setup.
I have a query as follows
QUERY1
void Main()
{var a = from cpuid in Computers
where cpuid.DnsHostName == "xyz"
select new {
ID = cpuid.TechnicalProductsHosted.Select (x => new { Id = x.Id }),
System_Dept = cpuid.SystemDepartment,
};
Console.WriteLine(a);
}
The output : it returns 4 ids but one department which is common among all four id's. When i query otherway round i.e
QUERY2
var a = from id in TechnicalProducts
where id.Id == "ID-15784"
select new
{System_Dept = id.Computers.Select(x => x.SystemDepartment),
Support_Team = id.Computers.Select(x => x.SupportTeam)
};
Console.WriteLine(a);
The output : 4 departments for the id. I wish to have the whole list of departments in the first case. How is it possible? In query 1 Can i take id as input for System Department and query it somehow?
the output samples

how to get last inserted id - zend

I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll