API return breaks when using inner join? - sql
I've been building an API which was working absolutely fine until I tried to add an inner join
The SQL I'm passing returns as I'd expect when I run it in Beaver (am using Mac)
However, when I try and access it via my API end point, instead of the combined results, I get only results from the table I added in the join
I presume am doing something really stupid ...
From my controller:
result = dbtest.FromDatabase(
"SELECT A.FAMILY_ID
,A.START_TIME
,A.END_TIME
,A.WORKER_ID
,A.WEEK_NO
,A.ID
,A.SHIFT_NO
,A.DAY_OF_WEEK
,A.HOLIDAY_OR_TERM
,B.WORKER_NAME
FROM SHIFT_REQ_TBL A
INNER JOIN WORKER_TBL B ON A.WORKER_ID = B.WORKER_ID
WHERE A.FAMILY_ID = '" + FAMILY.FAMILY_ID + "'");
From my model
if (query.Contains("SHIFT_REQ_TBL"))
{
var tbl_type = new TimekeeperTables.SHIFT_REQ_TBL();
tbl_type.FAMILY_ID = Convert.ToInt32(reader["FAMILY_ID"]);
tbl_type.ID = Convert.ToInt32(reader["ID"]);
tbl_type.WEEK_NO = Convert.ToInt32(reader["WEEK_NO"]);
tbl_type.WORKER_ID = Convert.ToInt32(reader["WORKER_ID"]);
tbl_type.SHIFT_NO = reader["SHIFT_NO"].ToString();
tbl_type.START_TIME = reader["START_TIME"].ToString();
tbl_type.END_TIME = reader["END_TIME"].ToString();
tbl_type.DAY_OF_WEEK = reader["DAY_OF_WEEK"].ToString();
tbl_type.HOLIDAY_OR_TERM = reader["HOLIDAY_OR_TERM"].ToString();
tbl_type.WORKER_NAME = reader["WORKER_NAME"].ToString();
db_results.Add(tbl_type);
jsonDoc = JsonConvert.SerializeObject(db_results);
}
Results (from postman)
"[{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"},{\"WORKER_ID\":1,\"WORKER_NAME\":\"UNASSIGNED\"}]"
I'm sorry, I was being stupid and figured it out
I was using a really dumb way of identifying the calling URL which already was checking for SHIFT_TBL in an earlier case
Related
Symfony 4.2 Build request
I'm building a request in Symfony but i have an error "$products not define". How should i do to make a good definition? Do u find another problem in my request? Any amelioration which is possible? Thank you! public function findEtudiantPasPointer($em, $utilisateurProf, $idCours, $idDate, $idCreneau) { $query = $em->createQuery(" SELECT u.nomUtilisateur, u.prenomUtilisateur FROM App\Entity\Pointage po LEFT JOIN App\Entity\EtudiantCours ec ON po.utilisateurEtudiant = ec.etudiant JOIN App\Entity\Utilisateur u ON po.utilisateurEtudiant = u.id JOIN App\Entity\CoursPlanning cp ON po.cours = cp.cours AND cp.cours = :idCours AND cp.plageHoraire = :idCreneau AND cp.dateCours = :idDate AND cp.cours = :idCours AND cp.id = po.cours AND ec.cours = c.id ") ->setParameter('idCours', $idCours); ->setParameter('idDate', $idDate); ->setParameter('idCreneau', $idCreneau); $products = $query->getResult(); return $products; }
You are missing the ; semicolon symbol: // before ->setParameter('idCours', $idCours) ->setParameter('idDate', $idDate) ->setParameter('idCreneau', $idCreneau) // after ->setParameter('idCours', $idCours) ->setParameter('idDate', $idDate) ->setParameter('idCreneau', $idCreneau); // <---- HERE! Also in DQL there's no ON when joining, should be WITH instead. Read the DQL's documentation how to query related entities properly.
the multi part identifier could not be bound in an update query
First of all I've looked at similar questions but failed to find one for my case. The access code i am turning into sql is as follows (I didn't write it) UPDATE QUpdateTrialstepApproved1 INNER JOIN TrialStepApproved ON QUpdateTrialstepApproved1.cid_req = TrialStepApproved.cID SET TrialStepApproved.wm21 = [wm2_req], TrialStepApproved.sw = [startweek_req], TrialStepApproved.PlannedTotalm2 = [m2_req], TrialStepApproved.ew = [endweek_req], TrialStepApproved.ActualNrofDiffEntries = [entries_req], TrialStepApproved.entryfactorTrial1 = [eFtrial_req], TrialStepApproved.fixeddeliveryweek = [fixedEndweek_req], TrialStepApproved.culturename = [culturename_req] WHERE (((QUpdateTrialstepApproved1.approveRequestChange)="v") AND ((TrialStepApproved.Location) Is Not Null)); I've turned it into the following but I get the error in the title: UPDATE A SET B.wm21 = [wm2_req], B.sw = [startweek_req], B.PlannedTotalm2 = [m2_req], B.ew = [endweek_req], B.ActualNrofDiffEntries = [entries_req], B.entryfactorTrial1 = [eFtrial_req], B.fixeddeliveryweek = [fixedEndweek_req], B.culturename = [culturename_req] from QUpdateTrialstepApproved1 as A INNER JOIN TrialStepApproved as B ON A.cid_req = B.cID WHERE A.approveRequestChange='v' AND B.Location Is Not Null
You're updating B, not A. Change the first line to UPDATE B ...and thing will work fine. An SQLfiddle.
How to write the HAVING clause with SQL COUNT(DISTINCT column_name) function in Codeigniter Active Record?
I am using Codeigniter and am trying to use the Active Record Class for all my database operations. However, I did run into problems when trying to convert the last bid of the following (working) query into Active Record code. $sql = ("SELECT ac.cou_id FROM authorcourse ac INNER JOIN course c ON ac.cou_id = c.cou_id WHERE cou_name = ? // ? = $cou_name AND cou_number = ? // ? = $cou_number AND cou_term = ? // ? = $cou_term AND cou_year = ? // ? = $cou_year AND FIND_IN_SET (ac.aut_id, ?) //? = $aut_ids_string GROUP BY ac.cou_id HAVING COUNT(DISTINCT ac.aut_id) = ? //? = $aut_quantity AND COUNT(DISTINCT ac.aut_id) = (SELECT COUNT(DISTINCT ac2.aut_id) FROM authorcourse ac2 WHERE ac2.cou_id = ac.cou_id)"); $query = $this->db->query($sql, array($cou_name, $cou_number, $cou_term, $cou_year, $aut_ids_string, $aut_quantity)); Question: How do I convert the HAVING clause into valid Active Record code? I tried using $this->db->having(); and $this->db->distinct(); but failed to combine the functions to achieve the desired result. My (working) code so far: $this->db->select('ac.cou_id'); $this->db->from('authorcourse ac'); $this->db->join('course c', 'c.cou_id = ac.cou_id'); $this->db->where('cou_name', $cou_name); $this->db->where('cou_number', $cou_number); $this->db->where('cou_term', $cou_term); $this->db->where('cou_year', $cou_year); $this->db->where_in('ac.aut_id',$aut_ids); $this->db->group_by('ac.cou_id'); // missing code Thanks a lot!
You code seems quite clumsy. But, you can use having clause in the following way: $this->db->having("ac.aut_id = '".$aut_qty."'", null, false)
Problems translating an SQL query to LINQ in VS Lightswitch
So, I am having an issue with an SQL query that is translated LINQ (and works - tested), but that same LINQ query does not work in Lightswitch. Of course I did not expect to work straight out, but I am struggling to properly convert it. So here is a image of the tables that I base my query on: http://dl.dropbox.com/u/46287356/tables.PNG (sorry for outside link, but not enough rep points :)) The SQL query is the following: SELECT WorkingUnits.Name AS WUName, ContractPositions.WUInstanceId, Materials.Cost, BillingValues.Value, BillingValues.PricePerUnit FROM WorkingUnits INNER JOIN Materials ON WorkingUnits.Id = Materials.Material_WorkingUnit INNER JOIN ContractPositions ON Materials.Id = ContractPositions.ContractPosition_Material INNER JOIN BillingValues ON ContractPositions.Id = BillingValues.BillingValue_ContractPosition Now, I have transformed this to LINQ in the following way: var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits join m in this.DataWorkspace.ApplicationData.Materials on new { Id = WorkingUnits.Id } equals new { Id = m.Material_WorkingUnit } join cp in this.DataWorkspace.ApplicationData.ContractPositions on new { Id = m.Id } equals new { Id = cp.ContractPosition_Material } join bv in this.DataWorkspace.ApplicationData.BillingValues on new { Id = cp.Id } equals new { Id = bv.BillingValue_ContractPosition } select new { usage = bv.Value * bv.PricePerUnit, totalCost = (bv.Value * bv.PricePerUnit) * m.Cost, amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice }; Notice that I have changed a few things - like section of colums, as I do not need that in Lightswitch. So while this works agains the SQL server, Lightswitch complains that I must consider explicitly specifying the type of the range variable 'WorkingUnits'. I tried to cast it, but then there are other errors such as: 'int' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) So my questions is, how do I properly convert that query and expect it to work? Also, If we take that my database is setup correctly, do I even need to use 'joins' in the LINQ? Any ideas are appreciated!
try something like this var query = from wu in this.DataWorkspace.ApplicationData.WorkingUnits join m in this.DataWorkspace.ApplicationData.Materials on wu.Id equals m.WorkingUnitID } join cp in this.DataWorkspace.ApplicationData.ContractPositions on m.Id equals cp.ContractPosition_Material join bv in this.DataWorkspace.ApplicationData.BillingValues on cp.Id equals bv.BillingValue_ContractPosition select new { usage = bv.Value * bv.PricePerUnit, totalCost = (bv.Value * bv.PricePerUnit) * m.Cost, amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice };
What about starting at the bottom (BillingValues) and working your way up using the entity references? eg var query = from bv in this.DataWorkspace.ApplicationData.BillingValues let m = bv.ContractPosition.Material let wu = m.WorkingUnit select new { usage = bv.Value * bv.PricePerUnit, totalCost = (bv.Value * bv.PricePerUnit) * m.Cost, amount = (bv.Value*bv.PricePerUnit) * m.Cost / wu.WUPrice };
Performing PostgreSQL LEFT OUTER JOINS and CASEs in Django
So I have a fairly involved sql query here. SELECT links_link.id, links_link.created, links_link.url, links_link.title, links_category.title, SUM(links_vote.karma_delta) AS karma, SUM(CASE WHEN links_vote.user_id = 1 THEN links_vote.karma_delta ELSE 0 END) AS user_vote FROM links_link LEFT OUTER JOIN auth_user ON (links_link.user_id = auth_user.id) LEFT OUTER JOIN links_category ON (links_link.category_id = links_category.id) LEFT OUTER JOIN links_vote ON (links_vote.link_id = links_link.id) WHERE (links_link.id = links_vote.link_id) GROUP BY links_link.id, links_link.created, links_link.url, links_link.title, links_category.title ORDER BY links_link.created DESC LIMIT 20 All my relations are good (I think) and this query works perfectly when I run it in my navicat for postgresql but turning it into something Django can use has been quite the challenge. I am using the pre-alpha 1.2 development verison (from the subversion repositories) so I have full range of tools from the docs. Here are my models for grins: class Category (models.Model): created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) title = models.CharField(max_length = 128) def __unicode__(self): return self.title class Link (models.Model): category = models.ForeignKey(Category) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) fame = models.PositiveIntegerField(default = 1) url = models.URLField(max_length = 2048) title = models.CharField(max_length = 256) active = models.BooleanField(default = True) def __unicode__(self): return self.title class Vote (models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) karma_delta = models.SmallIntegerField(default = 1) def __unicode__(self): return str(self.karma_delta) How I am able to turn def latest(request): links = Link.objects.all().order_by('-created')[:20] return render_to_response('links/list.html', {'links': links}) Into the above query? I've only been able to make some progress using things like Aggregation but how to tackle my use of CASE is beyond me. Any help would be much appreciated. I always prefer to work in a framework's built in ORM but if raw SQL is necessary...
I don't have time at the moment to attempt a full translation of that query, but if the CASE is your main stumbling block, I can tell you right now it isn't supported natively, you'll need to use a call to .extra() with some raw SQL for that. Something like: .extra(select={'user_vote': 'SUM(CASE WHEN links_vote.user_id = 1 THEN links_vote.karma_delta ELSE 0 END')}) But if this query works well as-is, why bother translating it into the ORM? Just grab a cursor and run it as a SQL query. Django's ORM is intentionally not a 100% solution, there's a reason it exposes the raw cursor API. Update: And since Django 1.2, there's also Manager.raw() to let you make raw SQL queries and get model objects back (thanks Van Gale).