SQL Get Order by 2 date colums when join 3 tables - mysql

My tables:
T1 = Projects
T2 = bid_details
T3 = bid_submission_details
T4 = quote_submission_details
This is how Data flow Works:
SQL Code:
"SELECT *,T3.bidsubmit_date,T4.Quotesubmit_date FROM `Projects` T1
LEFT JOIN `bid_details` T2 ON(T2.proj_reff = T1.proj_reff)
LEFT JOIN `bid_submission_details` T3 ON(T3.bid_reff = T2.bid_reff)
LEFT JOIN `quote_submission_details` T4 ON(T4.proj_reff = T1.proj_reff)
ORDER BY T3.bidsubmit_date,T4.Quotesubmit_date ASC";
Result View:
I have tried many ways to ORDER BY the submission date. but nothing worked. In the result view blue highlighted row is 2014 dated but it not going at the top of the list when I Order by Ascending order.
It always Orders the result from Quote Submission table first and then Order the result from Bid Submission table. Project types can be seen the in the result view.
i want a way to get Order by submission date no matter what type of project it is!

using COALESCE() function to the filed from the other three tables together.
SELECT *,T3.bidsubmit_date,T4.sub_date,
COALESCE(T3.bidsubmit_date,T4.sub_date) AS SubmiDates
FROM `$SQLTable` T1
LEFT JOIN `quote_submission_details` T4 ON(T4.pro_ref_no = T1.ref_no)
LEFT JOIN `bid_details` T2 ON(T2.pro_ref_no = T1.ref_no)
LEFT JOIN `bid_submission_details` T3 ON(T3.bid_ref_no = T2.bid_ref_no)
ORDER BY SubmiDates ASC";
after many very much goggling found a solution !!!

Related

Collapse rows with equal values in particular columns in one

I have a table with deals data written in it. I need to query said deals while joining on other tables, however d.originalorderid is not a unique entry and I get several duplicate entries. I want to:
For each unique d.originalorderid select one row
This row should be most recent (largest ID)
How would I go about this? This is the query I have right now.
SELECT d.id,
d.date,
d.ip, d.panmask,
d.merchantorderid,
d.amount,
d.cardholder,
d.bankhumanname,
d.cardtypeid,
d.bankcountrycode,
d.usercountrycode,
mc.paymentkey as merchantname,
dt.status,
d.merchantcontract,
dt.tag,
d.originalorderid,
ds.refnumber,
ds.dealauthcode,
mc.processingid,
pc.Name as processing,
d.customparams
FROM Deal as d
LEFT JOIN MerchantContract as mc ON mc.Id = d.MerchantContract
LEFT JOIN DealTrace as dt ON d.Id = dt.DealId
AND dt.id = (SELECT MAX(id)
FROM DealTrace WITH (nolock)
WHERE DealId = d.id)
LEFT JOIN DealSummary ds ON d.Id = ds.DealId
AND ds.id = (SELECT MAX(id)
FROM DealSummary WITH (nolock)
WHERE DealId = d.id)
LEFT JOIN Processing pc on mc.ProcessingId = pc.id
WHERE (d.MerchantContract IN ('12'))
ORDER BY ID desc OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY
If I understand the requirement, instead of joining to the Deal table, join to a correlated subquery on it which returns the deal with the highest deal id which has the same original order id. Test it but I think its OK..
SELECT ....
FROM
(SELECT *
FROM Deal d1
WHERE d1.Id=(SELECT MAX(Id)
FROM Deal d2
WHERE d2.OriginalOrderId=d1.OriginalOrderId)) d
LEFT JOIN MerchantContract as mc ON mc.Id = d.MerchantContract
etc etc

Mysql query with group by and order by involving several tables

I'm having a problem regarding a query because i don't have all the records and i don't know why
This is the query
SELECT `ebspma_paad_ebspma`.`semana_dias`.`dia`,`ebspma_paad_ebspma`.`req_material_sala`.`sala`, `ebspma_paad_ebspma`.`req_material_tempo`.`inicio`, `ebspma_paad_ebspma`.`sala_ocupacao`.`id_ocup`, `ebspma_paad_ebspma`.`turmas`.`turma`
FROM `ebspma_paad_ebspma`.`sala_ocupacao`
INNER JOIN `ebspma_paad_ebspma`.`semana_dias`
ON (`sala_ocupacao`.`id_dia` = `semana_dias`.`id_dia`)
INNER JOIN `ebspma_paad_ebspma`.`req_material_sala`
ON (`sala_ocupacao`.`id_sala` = `req_material_sala`.`idsala`)
LEFT JOIN `ebspma_paad_ebspma`.`req_material_tempo`
ON (`sala_ocupacao`.`id_tempo` = `req_material_tempo`.`idtempo`)
LEFT JOIN `ebspma_paad_ebspma`.`turmas`
ON (`sala_ocupacao`.`id_turma` = `turmas`.`id_turma`)
where`ebspma_paad_ebspma`.`sala_ocupacao`.`id_turma` = '$turma'
GROUP BY `ebspma_paad_ebspma`.`sala_ocupacao`.`id_dia` , `ebspma_paad_ebspma`.`req_material_tempo`.`inicio` ASC";
Running this query i have almost records but this is a school timetable and when a class is divided in 2 groups i have two classrooms for this class. With this query i have only one group
For exemple the class start at 1 PM in two classrooms (27 and 31), with this query i should have at 1 PM the classroom X is on 27 and 31 classroom, but i have only the first one
Image to check http://postimg.org/image/u24r35fkz/
And my database image http://postimg.org/image/hyvpb1qz1/ce7a7320/
So what's wrong with my query?
Thanks
UPDATE 1
I have simplified my query to
SELECT t2.`dia` , t3.`sala` , t4.`inicio` , t1.`id_ocup` , t5.`turma`
FROM `ebspma_paad_ebspma`.`sala_ocupacao` AS t1
INNER JOIN `ebspma_paad_ebspma`.`semana_dias` AS t2 ON ( t1.`id_dia` = t2.`id_dia` )
INNER JOIN `ebspma_paad_ebspma`.`req_material_sala` AS t3 ON ( t1.`id_sala` = t3.`idsala` )
LEFT JOIN `ebspma_paad_ebspma`.`req_material_tempo` AS t4 ON ( t1.`id_tempo` = t4.`idtempo` )
LEFT JOIN `ebspma_paad_ebspma`.`turmas` AS t5 ON ( t1.`id_turma` = t5.`id_turma` )
WHERE t1.`id_turma` =12
GROUP BY t1.`id_dia` , t3.`idsala` , t4.`inicio`
Now i can see all the classes but not in the right order, the order should be given by t4.inicio and by day (id dia)
You are not grouping by sala so MySQL will behave badly and give you a random row that fits the other requirements. Better functioning database engines would give you an error saying you haven't aggregated or grouped all result columns.
If you add sala to GROUP BY you should see the difference.
For the ordering: you're not asking the database to ORDER BY anything so the rows will be in whatever order they happen to come out. Probably want to add ORDER BY t4.inicio, t1.id_dia to handle that.

MySQL selecting multi ids values in one row

Here is query:
SELECT
t1.id, t1.data, t1.invoice_nr, t3.tiekejas, t4.uzsakovas, t1.pard_suma, t1.pirk_suma,
t1.transporto_suma, t2.apm_id, t2.apm_data, t2.apm_suma, t2.tipas, t1.terminas,
t5.regionas, t6.imone, t1.masina, t7.vardas, t7.pavarde, t8.vardas, t8.pavarde
FROM
irasai t1
LEFT JOIN apmokejimai t2 ON t1.invoice_nr = t2.apm_invoice_nr
LEFT JOIN tiekejai t3 ON t1.tiekejas = t3.id
LEFT JOIN uzsakovai t4 ON t1.pirkejas = t4.id
LEFT JOIN regionai t5 ON t1.regionas = t5.id
LEFT JOIN transportas t6 ON t1.transporto_imone = t6.id
LEFT JOIN vadybininkai t7 ON t1.pard_vad = t7.id
LEFT JOIN vadybininkai t8 ON t1.pirk_vad = t8.id
GROUP BY t1.invoice_nr, t2.apm_id
ORDER BY t1.data, t1.invoice_nr
And the problem is that table t1 some columns(tiekejas, pirkejas, regionas, trasporto_imone, pard_vad, pirk_vad) is sets of ids(ex. 1,2,5 etc). This query returns value only of one id from set, I want to get it all in one row (every value in new line or separated by dot or something, I can split them later in program). For now I split them in program, but I was required to select them one by one from database, and that takes too much time, and programs working too slow then.
I hope there is a better solution for this. Thanks.
HERE IS SQL FIDDLE LINK: http://sqlfiddle.com/#!9/d8609/1
EDIT:
http://postimg.org/image/3sostf42n/
This what I need to get, defined column is t1.tiekejas (ex. 1,2,5), this ids have values in table t3 (tiekejai), by this query it only returns one value by id 1, but I need three values of ids 1,2,5 returned.
Your initial problem can be fixed using FIND_IN_SET:-
SELECT
t1.id, t1.data, t1.invoice_nr, t3.tiekejas, t4.uzsakovas, t1.pard_suma, t1.pirk_suma,
t1.transporto_suma, t2.apm_id, t2.apm_data, t2.apm_suma, t2.tipas, t1.terminas,
t5.regionas, t6.imone, t1.masina, t7.vardas, t7.pavarde, t8.vardas, t8.pavarde
FROM
irasai t1
LEFT JOIN apmokejimai t2 ON t1.invoice_nr = t2.apm_invoice_nr
LEFT JOIN tiekejai t3 ON FIND_IN_SET(t3.id, t1.tiekejas)
LEFT JOIN uzsakovai t4 ON FIND_IN_SET(t4.id, t1.pirkejas)
LEFT JOIN regionai t5 ON FIND_IN_SET(t5.id, t1.regionas)
LEFT JOIN transportas t6 ON FIND_IN_SET(t6.id, t1.transporto_imone)
LEFT JOIN vadybininkai t7 ON FIND_IN_SET(t7.id, t1.pard_vad)
LEFT JOIN vadybininkai t8 ON FIND_IN_SET(t8.id, t1.pirk_vad)
GROUP BY t1.invoice_nr, t2.apm_id
ORDER BY t1.data, t1.invoice_nr
However I think you are going to have issues with the multiple values from each joined table. Further you are using GROUP BY to eliminate the multiple rows, and which one of the various values for each column for a particular invoice_nr / apm_id that is chosen is not defined.
Note, also it is generally a bad idea to have a field containing a comma separated list of ids. It makes doing a join slow and harder than it should be (as indexes cannot effectively be used on the field), and it limits future increases in the data. It is generally a sign of a poorly normalised database design.

MySQL query with joins on a table where second table name comes from a column in the first table

I think my title says it all, but in essence, this is what I want to do:
SELECT t1.*, t2.friendly_name, CONCAT_WS(" ",t3.name,t3.surname) AS user FROM activity
LEFT JOIN t1.typedb AS t2 ON t1.typeid = t2.id
LEFT JOIN users AS t3 on t1.loginid = t2.loginid
ORDER BY time DESC, user ASC
But as you can imagine, this will give me an error.
I can do a normal select on the activity db and then do a loop in php and run queries to fetch the info. But there has to be a way to do this in one query in MYSQL.
Please help.
So there is a table name in typedb? Then no, SQL doesn't support this. This is not how a relational database is supposed to work.
You can try something along the lines of
SELECT
t1.*,
coalesce(x1.friendly_name, x2.friendly_name, x3.friendly_name) as friendly_name,
CONCAT_WS(" ",t3.name,t3.surname) AS user
FROM activity t1
LEFT JOIN tableX AS x1 ON t1.typeid = x1.id and t1.typedb = 'TABLEX'
LEFT JOIN tableY AS x2 ON t1.typeid = x2.id and t1.typedb = 'TABLEY'
LEFT JOIN tableZ AS x3 ON t1.typeid = x3.id and t1.typedb = 'TABLEZ'
LEFT JOIN users AS t3 on t1.loginid = coalesce(x1.loginid,x2.loginid,x3.loginid)
ORDER BY time DESC, user ASC;
But this is not very efficient. It's just not what SQL is made for. So use a programming language and build dynamic SQL, or even better: change your database design.

Need a more efficient join query

It's been a long time since I last did something with database so my knowledge has beenyet rusted. I have 2 SQL tables:
data(id, attr);
dependency(child, parent);
#**child** and **parent** are the id from table **data**
I need to query all the attr corresponding to the entries in table dependency. Following is my attempt:
SELECT
(SELECT data.attr FROM data WHERE data.id = child) AS child_attr,
(SELECT data.attr FROM data WHERE data.id = parent) AS parent_attr
from dependency;
It works but very slow. I'm sure there's a better way to do it with join query but cannot come up with it yet.
Can someone please help?
Thanks,
You could join the dependency table to the data table twice to get the information you need:
SELECT d1.attr AS ChildAttr, d2.attr AS ParentAttr
FROM dependency AS dep
INNER JOIN data AS d1 ON dep.child = d1.id
INNER JOIN data AS d2 ON dep.parent = d2.id
try this:
SELECT t2.attr, t3.attr
FROM dependency as t1
INNER JOIN data as t2 on t1.child = t2.id
INNER JOIN data as t3 on t1.parent = t3.id