I want create that query
SELECT * FROM `books` INNER JOIN (SELECT * FROM `authors` GROUP by `author_id`) as variable ON variable.`id` = `books`.`id` INNER JOIN `student` ON `student`.`id` = variable.`id` WHERE (`books`.`id` = '1');
For the question, of course, the request itself is slightly changed, but that's not the point. Can you please help me to make this kind of request in Ruby on Rails style
I tried, but it's a bit not what I want ... I have to do INNER JOIN (Select ... )
Book.select('*').joins(author: :student).where("`books`.`id` = '1'").group("author.author_id")
While your SQL does not appear to make any logical sense you can construct this query as follows:
author_table = Author.arel_table
author_sub_query = Arel::Nodes::TableAlias.new(
author_table
.project(author_table[Arel.star])
.group(author_table[:author_id]), 'variable')
author_join = Arel::Nodes::InnerJoin.new(
author_sub_query,
author_sub_query.create_on(author_sub_query[:id].eq(Book.arel_table[:id])))
student_join = Arel::Nodes::InnerJoin.new(
Student.arel_table,
author_sub_query.create_on(Student.arel_table[:id].eq(author_sub_query[:id])))
Book
.select(Arel.star)
.joins(author_join,student_join)
.where(id: 1)
Which will produce:
SELECT
*
FROM
`books`
INNER JOIN (SELECT `authors`.* FROM `authors` GROUP BY `authors`.`author_id`) `variable`
ON `variable`.`id` = `books`.`id`
INNER JOIN `students`
ON `students`.`id`= `variable`.`id`
WHERE
`books`.`id` = 1
That being said I have no idea what you are trying to do with this but if the intent is to eager load this data, you could try making these changes to the above:
author_sub_query = Arel::Nodes::TableAlias.new(
author_table
.project(author_table[Arel.star])
.group(author_table[:author_id]), Author.table_name)
Book
.joins(author_join,student_join)
.eager_load(author: :student)
.where(id: 1)
Related
I want to create a view which combines the data with the maximal date from the tables shown in the picture. These should be grouped by the profileID.
Database ERM
The profileIDs are linked to profile.userID.
I tried different approches in my code. The fort one slects the data where date is max, but the join doesn't work. Every profileID will be joined with the same data.
CREATE
ALGORITHM = UNDEFINED
DEFINER = `b91788dd8d05b5`#`%`
SQL SECURITY DEFINER
VIEW fitchallengersql1.profileview AS
Select p.userID,
(SELECT
`bf`.`bodyFat`
FROM
(`fitchallengersql1`.`bodyfatprofile` `bf`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bf`.`profileID` = `p`.`userID`)
AND (`bf`.`date` = (SELECT
MAX(`fitchallengersql1`.`bodyfatprofile`.`date`)
FROM
`fitchallengersql1`.`bodyfatprofile`)))) AS `bodyFat`,
(SELECT
`bw`.`bodyweight`
FROM
(`fitchallengersql1`.`bodyweightprofile` `bw`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bw`.`profileID` = `p`.`userID`)
AND (`bw`.`date` = (SELECT
MAX(`fitchallengersql1`.`bodyweightprofile`.`date`)
FROM
`fitchallengersql1`.`bodyweightprofile`)))) AS `bodyWeight`,
(SELECT
`bmi`.`bmi`
FROM
(`fitchallengersql1`.`bmiprofile` `bmi`
JOIN `fitchallengersql1`.`profile` `p`)
WHERE
((`bmi`.`profileID` = `p`.`userID`)
AND (`bmi`.`date` = (SELECT
MAX(`fitchallengersql1`.`bmiprofile`.`date`)
FROM
`fitchallengersql1`.`bmiprofile`)))) AS `bmi`
From profile
In the second one the join works how it should, but I can't figure out a way to select just the data where date is max.
CREATE
ALGORITHM = UNDEFINED
DEFINER = `b91788dd8d05b5`#`%`
SQL SECURITY DEFINER
VIEW `fitchallengersql1`.`profileview` AS
SELECT
`p`.`userID` AS `userID`,
`p`.`privacy` AS `privacy`,
`bs`.`size` AS `bodysize`,
`bw`.`bodyweight` AS `bodyweight`,
`bf`.`bodyFat` AS `bodyfat`,
`bmi`.`bmi` AS `bmi`
FROM
((((`fitchallengersql1`.`profile` `p`
JOIN `fitchallengersql1`.`bodysizeprofile` `bs`)
JOIN `fitchallengersql1`.`bodyweightprofile` `bw`)
JOIN `fitchallengersql1`.`bmiprofile` `bmi`)
JOIN `fitchallengersql1`.`bodyfatprofile` `bf`)
WHERE
((`p`.`userID` = `bs`.`profileID`)
AND (`p`.`userID` = `bw`.`profileID`)
AND (`p`.`userID` = `bmi`.`profileID`)
AND (`p`.`userID` = `bf`.`profileID`))
Hope someone could help me.
Thank you!
fleewe
Hope following query gives what you need. Please follow the pattern and join the rest of the tables. Please note that when the table grows these will definitely have performance issues as this require huge processing.
-- Select the columns that you need
select p.*, lbp.*
from profile p
inner join (
-- get the latest bmiprofile per user profile
select bp1.*
from bmiprofile bp1
inner join (select profileID, max(date) as date from bmiprofile group by profileID) as bp2 on bp1.prfileId = bp2.profileId and bp1.date = bp2.date
) as lbp on lbp.ProfileId = p.userId
-- Join the other tables in similar way
this is only a comment, but I needed formating capability:
Don't place the joining predicates into the where clause if using ANSI join syntax, instead use ON followed by the relevant predicates. e.g.
FROM `fitchallengersql1`.`profile` `p`
JOIN `fitchallengersql1`.`bodysizeprofile` `bs` ON `p`.`userID` = `bs`.`profileID`
JOIN `fitchallengersql1`.`bodyweightprofile` `bw` ON `p`.`userID` = `bw`.`profileID`
JOIN `fitchallengersql1`.`bmiprofile` `bmi` ON `p`.`userID` = `bmi`.`profileID`
JOIN `fitchallengersql1`.`bodyfatprofile` `bf` ON `p`.`userID` = `bf`.`profileID`
I have a client that wants to have all products that do not have a price to show up behind all products that do have a price. In this case, I will change the product position to 999. But they have over 3,000 products and it will take me hours to do manually.
Is there a way to possibly update this through MySQL? I would have to connect two tables I know. catalog_category_product and catalog_product_entity_decimal I believe it is.
Now I know catalog_category_product has a field called product_id and catalog_product_entity_decimal has a field called entity_id which are essentially the same thing.
I figure there has to be a way to connect each of them somehow to make this happen.
EDIT: And yes, I know there is a Sort By that will do this, but they don't want to have the highest price to the lowest price showing as a default. They want to be able to position items they would like on the first fold.
1. Always do database backup before this kind of operation
2. use this to check if your result is correct:
SELECT *
FROM `catalog_category_product` AS `cpe`
INNER JOIN (
SELECT `e`.`entity_id`
FROM `catalog_product_entity` AS `e`
INNER JOIN `eav_attribute` AS `ea` ON `ea`.`attribute_code` = 'price'
INNER JOIN `catalog_product_entity_decimal` AS `at_price` ON (`at_price`.`entity_id` = `e`.`entity_id`) AND (`at_price`.`attribute_id` = `ea`.`attribute_id`)
WHERE ((at_price.value = '0') OR (((at_price.value = 'price') OR (at_price.value = '1'))))
) AS `result` ON cpe.product_id = result.entity_id;
3. and this to update position values:
UPDATE `catalog_category_product` AS `cpe`
INNER JOIN (
SELECT `e`.`entity_id`
FROM `catalog_product_entity` AS `e`
INNER JOIN `eav_attribute` AS `ea` ON `ea`.`attribute_code` = 'price'
INNER JOIN `catalog_product_entity_decimal` AS `at_price` ON (`at_price`.`entity_id` = `e`.`entity_id`) AND (`at_price`.`attribute_id` = `ea`.`attribute_id`)
WHERE ((at_price.value = '0') OR (((at_price.value = 'price') OR (at_price.value = '1'))))
) AS `result` ON cpe.product_id = result.entity_id
SET `cpe`.`position` = 999;
4. Notice this code shouldn't work with multistores.
5. Use it on your own risk:)
I have the following Mysql query. Running as needed.
SELECT
t_doc.*, t_user.IDA, t_data.IDA
FROM
( SELECT DISTINCT IDau FROM t_doc ) IDau_list
LEFT OUTER JOIN
(
SELECT
IDd ,IDau
FROM
t_doc
WHERE
doc_type = 'doc'
GROUP BY IDau
)
doc_images ON doc_images.IDau = IDau_list.IDau
LEFT OUTER JOIN
(
SELECT
IDd ,IDau
FROM
t_auto_doc
WHERE
doc_type = 'jpg'
GROUP BY IDau
)
jpg_images ON jpg_images.IDau = IDau_list.IDau
LEFT OUTER JOIN
t_doc ON t_doc.IDdoc = COALESCE(jpg_images.IDd, doc_images.IDd)
LEFT OUTER JOIN
t_user ON t_user.IDau = t_doc.IDau
LEFT OUTER JOIN
t_data ON t_user.IDA = t_data.IDA
But, What I must bring this query to codeigniter Model, in which I have to adapt the query, as example like this...
$this->db->select('u.IDau, a.*');
$this->db->from('t_user u');
$this->db->join('t_doc d', 'd.IDau=u.IDau', 'left');
And ...More.....Here......
But, I got it difficult. Is some one out there might change it Please..
Thanks in advance
As #NEVERMIND Suggest I have accomplish the task using...
$query = $this->db->query("My QUERY WITH A BIT OF CHANGE");
Yes, I should make some change to get the exact Data as i needed.
Thanks for all of your comments and ideas.
I am trying to create a query that will allow me to use multiple VarChars as a parameter in SSRS.
Here's the code:
Declare #CallCodes as VarChar(10)
Set #CallCodes = ('MORC30' , 'Morc60')
;
With Data
AS
(SELECT
VC.[CallCode]
,VC.[HospCode]
,VC.[HospMastID]
,VC.[ClientID]
,Row_Number () Over (Partition By HospMastID, VC.ClientID Order By HospMastID, VC.ClientID, GLCode) as Txn
FROM
[RptSys].[dbo].[CSC_VuesionImport_DevDetl] as VC
Inner Join
[AVimark_OLTP].[dbo].[Client] as C
on
VC.HospMastID = C.HospitalMasterID
and
VC.ClientID = C.ClientID
Inner Join
[Avimark_OLTP].[dbo].[Patient] as P
on
VC.HospMastID = P.HospitalMasterID
and
VC.PatientID = P.PatientID
Inner Join
[Avimark_OLTP].[dbo].[Treatment] as T
on
VC.HospMastID = T.HospitalMasterID
and
VC.MastReminder = T.Code
Where
VC.CallCode in #CallCodes)
This gives an error when I try to run it. The final output is to allow the end user to choose from a drop down list in an SSRS report I have tried all variations of in or like for the where statement.
Any suggestions would be greatly appreciated.
Why don't you take the Parmaeter in a temporary table marked with #
CREATE TABLE #tmp(
Callcodes varchar(10))
INSERT INTO #tmp
VALUES
('MORC30'),
('Morc60')
With Data
AS
(SELECT
VC.[CallCode]
,VC.[HospCode]
,VC.[HospMastID]
,VC.[ClientID]
,Row_Number () Over (Partition By HospMastID, VC.ClientID Order By HospMastID, VC.ClientID, GLCode) as Txn
FROM
[RptSys].[dbo].[CSC_VuesionImport_DevDetl] as VC
Inner Join
[AVimark_OLTP].[dbo].[Client] as C
on
VC.HospMastID = C.HospitalMasterID
and
VC.ClientID = C.ClientID
Inner Join
[Avimark_OLTP].[dbo].[Patient] as P
on
VC.HospMastID = P.HospitalMasterID
and
VC.PatientID = P.PatientID
Inner Join
[Avimark_OLTP].[dbo].[Treatment] as T
on
VC.HospMastID = T.HospitalMasterID
and
VC.MastReminder = T.Code
Where
VC.CallCode in (SELECT * FROM #tmp))
I hope this is what you are looking for, if not please tell me. Or like mentioned in the comments give a error message
Have a nice day & greets from Switzerland
Etienne
I am having a bit of trouble getting my syntax right for a nested mysql if statement. This is my current query which is fine. But what I need is the parent category. Heres where it confuses me.
Basically I need to add the parentid bit to my query (written in pseudo-code)
SELECT p.*,i.`image`,
( IF(`limitc1`.`parentid` IN (135,136), `limitc1`.parentid)
ELSEIF(`limitc2`.`parentid` IN (135,136), `limitc2`.parentid)
ELSEIF(`limitc3`.`parentid` IN (135,136), `limitc3`.parentid)
ELSEIF(`limitc4`.`parentid` IN (135,136), `limitc4`.parentid)
) as `parentid`
FROM `product` p
JOIN `productcategory` limitpc USING(productid)
LEFT JOIN `category` limitc1 ON (limitpc.`categoryid` = limitc1.`categoryid`)
LEFT JOIN `category` limitc2 ON (limitc1.`parentid` = limitc2.`categoryid`)
LEFT JOIN `category` limitc3 ON (limitc2.`parentid` = limitc3.`categoryid`)
LEFT JOIN `category` limitc4 ON (limitc3.`parentid` = limitc4.`categoryid`)
LEFT JOIN `productlink` l ON (p.`productid` = l.`targetid` OR p.`productid` = l.`sourceid`)
JOIN `productimage` i ON p.`productid` = i.`productid` AND i.`primary` = 1
WHERE (l.`sourceid` = 5471 OR l.`targetid` = 5471)
AND p.`visible` = 1
AND p.`websitevisible` = 1
AND p.`productid` != 5471
GROUP BY p.`productid`
LIMIT 8
Any ideas would be greatly appreciated! :-)
You want to use the case statement:
SELECT p.*,i.`image`,
(case when `limitc1`.`parentid` IN (135,136) then `limitc1`.parentid
when `limitc2`.`parentid` IN (135,136) then `limitc2`.parentid
when `limitc3`.`parentid` IN (135,136) then `limitc3`.parentid
when `limitc4`.`parentid` IN (135,136) then `limitc4`.parentid
end) as `parentid`
. . .
Not only does this do what you want to do, but it is also standard SQL. The if statement is specific to MySQL.