Trying to make query on condition - sql

I read most of the solutions here with similar questions and it did not solve my problem and I cannot find anything online that can help me.
I am trying to make query on condition where user_id = session user_id but I get error when I make INNER join
ambiguous column name
for this
public List<CartModelClass>getCarts1(){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = { "ID" , "user_id", "food_id", "quantity", "price", "origin", "destination","description","company_name","search_id"};
String sqltable2 = "OrderDetails LEFT JOIN OrderDetails WHERE user_id LIKE '%%' ";
qb.setTables(sqltable2);
Cursor c = qb.query(db,sqlSelect, null, null ,null ,null ,null);
final List<CartModelClass> result = new ArrayList<>();
if (c.moveToFirst()) {
do {
result.add(new CartModelClass(
c.getString(c.getColumnIndex("user_id")),
c.getString(c.getColumnIndex("food_id")),
c.getString(c.getColumnIndex("quantity")),
c.getString(c.getColumnIndex("price")),
c.getString(c.getColumnIndex("origin")),
c.getString(c.getColumnIndex("destination")),
c.getString(c.getColumnIndex("description")),
c.getString(c.getColumnIndex("company_name")),
c.getString(c.getColumnIndex("search_id"))
));
} while (c.moveToNext());
}
return result;
}
so I changed InnerJoin and made it just table where user_id like"%%" but I only get the last user_id who added to cart and show all data for all users
I want to show only added cart for user_id = session user_id so i can use it in here
loadListFood
private void loadListFood(){
sessionManager= new SessionManager(getActivity());
final Hashmap<String, String> user = sessionManager.getUserDetail();
user.get(USER_ID);
listdata = new Database(this.getContext.getCarts1());
for(CartModelClass order : listdata)
user_id = order.getUser_id
if(user.get(USER_ID).equals(user_id)){
listdata = new Database(this.getContext()).getCarts();
adapter = new CartAdapter(listdata, this.getContext());
recyclerView.setAdapter(adapter);
int total = 0;
for (CartModelClass order : listdata) {
total += (Integer.parseInt(order.getPrice())) * (Integer.parseInt(order.getQuantity()));
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
txtTotalPrice.setText(fmt.format(total));
}
}else {
Toast.makeText(getContext(), "No Cart Added", Toast.LENGTH_LONG).show();
}
}

You are self joining the table OrderDetails.
In this case you must set aliases to both copies of the table, like:
OrderDetails as o1 LEFT JOIN OrderDetails as o2 ...
Now in the ON clause you must qualify the column names properly, like:
ON o1.user_id = o2.something
If you don't, you get that error message, because the column name user_id could belong to either of the 2 copies of the table.
Also:
What is session user_id? Is it a column name?
If it is then the problem is that it contains a space in its name.
Enclose it in square brackets, so the statemnet should be:
OrderDetails as o1 LEFT JOIN OrderDetails as o2
ON o1.user_id = o2.[session user_id]

Related

How to write join query with multiple column - LINQ

I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();

Nhibernate Criteria retrieve child of parent with restriction on other child of parent

I need to be able to write the following query as a Criteria.
SELECT hist.*
FROM
Administration admin
INNER JOIN Item item ON item.AdministrationId = admin.AdministrationId
INNER JOIN ItemHistory hist ON hist.ItemId = item.ItemId
WHERE
item.itemId = #param
and hist.IsError =
(
SELECT (CASE status.errorType
WHEN 'Warning' THEN 0
ELSE 1
END
)
FROM
AdminStatus status
WHERE
status.AdministrationId = admin.AdministrationId
AND status.Group = 'Issues'
)
I'm pretty sure I'll need to do the sub query as a detached criteria:
var status = DetachedCriteria.For<AdminStatus>("status");
status.CreateAlias("status.Administration", "admin");
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Property("AdministrationId"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));
But I'm not sure how to join that with my primary criteria:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
But I'm not sure how to join that with my primary criteria:
Methods from Subqueries class glue detached sub-query with main criteria. Subqueries.PropertyEq in you case:
var criteria = Session.CreateCriteria<ItemHIstory>("hist");
criteria.CreateAlias("ItemHistory.Item", "item");
criteria.CreateAlias("item.Administration", "admin");
criteria.Add(Subqueries.PropertyEq("hist.IsError ", status))
And regarding detached criteria. Alias creation seems unnecessary:
var status = DetachedCriteria.For<AdminStatus>("status");
status.Add(Restrictions.EqProperty("status.AdministrationId", "admin.AdministrationId"));
status.Add(Restrictions.Eq("status.Group", "Issues"));
status.SetProjection(Projections.Conditional(
Restrictions.Eq("status.errorType", "Warning"),
Projections.Constant(0),
Projections.Constant(1)));

Dynamic column search in multiple tables with gorm golang

My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.

Problems with Left join Query LinqToSql

IBookingRepository bookingResp = new BookingRepository();
IQueryable<bookingTest> bookings = bookingResp.GetAllBookingsByView();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = from booking in bookings
join f in getallAttendees on booking.UserID equals f.UserID into fg
from fgi in fg.DefaultIfEmpty() //Where(f => f.EventID == booking.EventID)
where
booking.EventID == id
select new
{
EventID = booking.EventID,
UserID = booking.UserID,
TrackName = booking.Name,
BookingStatus = booking.StatusID,
AttendeeName = booking.FirstName,
// name = account.FirstName,
AmountPaid = booking.Cost,
AttendeeAddress = booking.DeliveryAdd1,
City = booking.DeliveryCity,
Postcode = booking.Postcode,
Date = booking.DateAdded,
hel = fgi == null ? null : fgi.HelmetsPurchased }// Product table
Hi, the above query doesnt executes it gives an error: The specified LINQ expression contains references to queries that are associated with different contexts. Any one can spot the what the problem is with the query.
I think that your getAllAttendees is from a different context than bookings so you won't be able to join them. To give a more exact answer you need to show where bookings and getAllAttendees comes from.

Joining tables in LINQ/SQL

I have below a collection of rows and each row consists of productid, unitid, countryid.
I need to find the details for each row in the corresponding tables (products, units, country)
for product - select product name, updatedby
for unitid - select unit name , updatedby
for countryid - select countryname, uploadby
and returning the rows which has the same format
Id = product id or unitid or countryid
name = proudct name or unit name or countryname
modified = product updatedby or unit updated by or country uploadby
So, in summary -
1. For a Collection of rows
a. use the id to get the extra details from the respective table
b. return the same type of collection for the results
2. do step 1 for
2.a For RegularToys (Run this logic on TableBigA)
2.b For CustomToys(Run this logic on TableB)
3. Return all the rows
by adding 2.a and 2.b
How to write an sql/linq query for this? thanks
If I'm understanding correctly, you want to use a given ID to find either a product, a unit or a country but you're not sure which. If that's the case, then you can build out deferred queries like this to find the given entity:
var prod = from p in db.Products
where p.ProductId = id
select new { Id = p.ProductId, Name = p.ProductName, Modified = p.UpdatedBy };
var unit = from u in db.Units
where p.UnitId = id
select new { Id = u.UnitId, Name = u.UnitName, Modified = p.UpdatedBy };
var ctry = from c in db.Countries
where c.CountryId = id
select new { Id = c.CountryId, Name = c.CountryName, Modified = c.UploadBy };
And then execute the queries until you find an entity that matches (with ?? being the null-coalesce operator that returns the right value if the left result is null).
var res = prod.SingleOrDefault() ??
unit.SingleOrDefault() ??
ctry.SingleOrDefault() ??
new { Id = id, Name = null, Modifed = null };
Without any further details I can't be more specific about the condition below, but I think you are asking for something along these lines. I'm assuming your Id's are int's (but this can be easily changed if not) and you already have an Entity Data Model for the tables you describe.
Create a class for your common data:
class RowDetail
{
public int Id { get; set; }
public string Name { get; set; }
public string Modified { get; set; }
}
Pull the information out of each of the sub tables into a new record:
IEnumerable<RowDetail> products =
from p in db.Products
where <<CONDITION>>
select
new RowDetail()
{
Id = p.ProductId,
Name = p.ProductName,
Modified = p.UpdatedBy
};
IEnumerable<RowDetail> units =
from u in db.Units
where <<CONDITION>>
select
new RowDetail()
{
Id = u.UnitId,
Name = u.UnitName,
Modified = u.UpdatedBy
};
IEnumerable<RowDetail> countries =
from c in db.Countries
where <<CONDITION>>
select
new RowDetail()
{
Id = c.CountryId,
Name = c.CountryName,
Modified = c.UploadBy
};
Finally pull all the records together in a single collection:
IEnumerable<RowDetail> results = products.Union(units).Union(countries);
I'm not sure if this is exactly what you are looking for, so feel free to give feedback and/or more details if further assistance is required.