Mysql 4 to 5 query conversion - join headaches - mysql

If anyone can help me rewrite my query to work in mysql 5 I would be very grateful. If anyone can provide links to solid, simple tutorials on how to rewrite old queries that would also be great.
My current (version 4) query looks like this:
SELECT
course.course_code,
course.course_title_sv AS course_title,
course.course_u_credits,
course.course_successive_level_scb_id,
s.successive_level_scb_order,
s.successive_level_scb_code,
LEFT (education_level.edu_level_name_sv, 1) AS course_edu_level, course.course_level,
GROUP_CONCAT(DISTINCT h.head_area_hv_title_sv SEPARATOR ', ') AS head_area_hv
FROM
course, course_event, course_event_package_links, package, education_level
LEFT JOIN
course_has_head_area_hv ON(course.course_id = course_has_head_area_hv.course_id)
LEFT JOIN
head_area_hv h ON(h.head_area_hv_id = course_has_head_area_hv.head_area_hv_id)
LEFT JOIN
successive_level_scb s ON(s.successive_level_scb_id = course.course_successive_level_scb_id)
WHERE
course.course_edu_level=education_level.edu_level_id AND
course.course_id=course_event.course_id AND
course_event.course_event_id=course_event_package_links.course_event_id AND
course_event_package_links.package_id=package.package_id AND
course.course_successive_level_scb_id != '' AND
package.package_id='6318'
GROUP BY course.course_id

Simply replace
SELECT ...
FROM course, course_event, course_event_package_links
...
WHERE course.course_id=course_event.course_id
AND course_event.course_event_id=course_event_package_links.course_event_id
by
SELECT ...
FROM course
JOIN course_event ON course_event.course_id = course.course_id
JOIN course_event_package_links
ON course_event_package_links.course_event_id = course_event.course_event_id
...
About your error message, are you sure course.course_id exists? Maybe it was replaced by course.course_code?

Related

SQL is intermittently returning no data in response to a LEFT JOIN

I am trying to hunt down a bug in a SQL query but can't seem to get to the bottom of it. The query looks like this:
SELECT
DATE(BT.DateCheckedIn) AS X,
DAYOFWEEK(BT.DateCheckedIn) AS DayX,
SUM(IR.QtyCheckedIn) AS C,
AU.AdminUsername,
AU.AdminFirstName,
AU.AdminLastName,
IF(BTE.ProdLogID IS NULL, 'No', 'Yes') AS Exclude
FROM
buying_issuesreceived IR
JOIN buying_transactions BT ON IR.TransactionID = BT.TransactionID
JOIN adminusers AU ON BT.CheckedInByAdminUserID = AU.AdminUserID
LEFT JOIN log_production_bt BTE
ON DATE(BT.DateCheckedIn) = DATE(BTE.ProductionDate)
AND BTE.ProductionSection = 'wtransactions'
AND AU.AdminUsername = BTE.ProductionUsername
WHERE
DATE(BT.DateCheckedIn) BETWEEN DATE '2018-09-24' AND DATE '2018-09-30'
GROUP BY
DATE(BT.DateCheckedIn),
AU.AdminUsername
When this query is run, it has about a 50/50 chance of returning the correct data or returning nothing at all. There is no error message. I know, or rather should say, am pretty certain, that the LEFT JOIN is the culprit because when I delete it from the code I stop getting empty tables, but can't, for the life of me, figure out why this query would return inconsistent results in the first place.
This sounds like a MySQL bug. As a workaround, you can use EXISTS with a correlated subquery.
SELECT
DATE(BT.DateCheckedIn) AS X,
DAYOFWEEK(BT.DateCheckedIn) AS DayX,
SUM(IR.QtyCheckedIn) AS C,
AU.AdminUsername,
AU.AdminFirstName,
AU.AdminLastName,
IF(EXISTS(
SELECT 1
FROM log_production_bt BTE
WHERE
DATE(BT.DateCheckedIn) = DATE(BTE.ProductionDate)
AND BTE.ProductionSection = 'wtransactions'
AND AU.AdminUsername = BTE.ProductionUsername), 'NO', 'YES') AS Exclude
FROM
buying_issuesreceived IR
JOIN buying_transactions BT ON IR.TransactionID = BT.TransactionID
JOIN adminusers AU ON BT.CheckedInByAdminUserID = AU.AdminUserID
WHERE
DATE(BT.DateCheckedIn) BETWEEN DATE '2018-09-24' AND DATE '2018-09-30'
GROUP BY
DATE(BT.DateCheckedIn),
AU.AdminUsername

Use of Pivot in SQL statement?

I'm attempting to create additional columns for when a drive record has multiple other records assigned to the drive. In my attached screenshot, you can see there are three drives where all data is constant, but each has multiple incentives assigned to the drive.
Would a PIVOT function work to create an additional column for the incentive? I'm not looking for something dynamic and I would be OK with hard coding at the most 4 additional columns to have space for five incentives assigned to one drive.
What I would like my results to look like would be:
The last column is how I performed used For XML Path to accomplish it, but it's not exactly what I was looking for.
Here is my SQL statement:
Select
DM.DriveID [DriveID],
DM.FromDateTime [FromDateTime],
Case When DM.OwnerType = 0 Then Acct.Name Else CD.DescLong End As [OwnerName],
Acct.AccountID [AcctID],
Inc.Description [Incentive],
Stuff ((Select ', ' + isnull(EM.Description,'')
From Production.[dbo].EquipmentMaster EM
Inner Join Production.[dbo].EquipmentDetail ED On EM.EquipmentID = ED.EquipmentID And EM.EquipmentType=3
Where ED.DriveID = DM.DriveID
For XML PATH(''), TYPE).value('.', 'varchar(max)')
,1, 2, '') as [XML_Incentives]
From
Production.[dbo].rpt_DriveMaster DM
Left Outer Join Production.[dbo].rpt_Accounts Acct on DM.AccountID=Acct.AccountID
Inner Join Production.[dbo].rpt_CenterDetail CD on DM.CenterID=CD.CenterID
Left Outer Join Production.[dbo].OBI_Incentives Inc on DM.DriveID=Inc.DriveID
Where
DM.DriveID in (658946,597611,651136)
I'm looking at the link provided when marked as duplicate, but is almost like reading Greek to me. I'm trying to modify my SQL to use this as a basis, but not having much luck:
Any chance on some guidance on how this works?
Select
*
From
( Select
DM.DriveID [DriveID],
DM.FromDateTime [FromDateTime],
Case When DM.OwnerType = 0 Then Acct.Name Else CD.DescLong End As [OwnerName],
Acct.AccountID [AcctID],
Inc.Description [Incentive1],
null [Incentive2],
null [Incentive3],
null [Incentive4],
null [Incentive5]
From
Production.[dbo].rpt_DriveMaster DM
Left Outer Join Production.[dbo].rpt_Accounts Acct on DM.AccountID=Acct.AccountID
Inner Join Production.[dbo].rpt_CenterDetail CD on DM.CenterID=CD.CenterID
Left Outer Join Production.[dbo].OBI_Incentives Inc on DM.DriveID=Inc.DriveID
Where
DM.DriveID in (658946,597611,651136)
) as P
Pivot (
min(P.[Incentive])
for P.[DriveID] in ([Incentive1], [Incentive2], [Incentive3])
) as PIV

How to access subquery table in the main query with MySQL?

select m1.id, m1.status, at.view_data, at.view_graph, ta.tag_string
from
access_tbl at, image_campaign_tbl m1
RIGHT JOIN
(select
GROUP_CONCAT(t.name) as tag_string , c.image_campaign_id
from campaign_tags_tbl c,tag_tbl t
where c.tag_id=t.id
$tag_q
group by c.image_campaign_id
) as ta
ON ta.image_campaign_id=m1.id
where
m1.client_id =$client_id
and m1.client_id = at.client_id
$prev_filter
limit $start,$end;
Error message:
in LOGS: DBD::mysql::db selectall_arrayref failed: Unknown column 't.name' in 'where clause' at /home/sakthi/rtads/Project/pm/Image/UI.pm line 2536.**
In Perl Module, I'm passing the same value of $tag_q to the $prev_filter to get the Pagination of filter based on TAGS values in the next page
if ( $prev_filter eq '' ) {
$prev_filter =
$search_clist_q . ' '
. $tag_q . ' '
}
From the error msg, I got the error which I'm doing. Since I'm trying to access the table of subquery in the main query, this error is happening.
So I want to know how to access the tag_string(or)t.name outside the subquery.
First of all, i suggest you to avoid use of old school syntax for jointures (FROM table1, table2,... WHERE table1.column1 = table2.column2 AND ...).
Here is the query that seems to return what you're looking for:
SELECT IC.id
,IC.status
,A.view_data
,A.view_graph
,TA.tag_string
FROM access_tbl A
INNER JOIN image_campaign_tbl IC ON IC.client_id = A.client_id
AND IC.client_id = $client_id
RIGHT JOIN (SELECT CT.image_campaign_id
,GROUP_CONCAT(T.name) AS [tag_string]
FROM campaign_tags_tbl CT
INNER JOIN tag_tbl T ON T.id = CT.tag_id
GROUP BY CT.image_campaign_id) TA ON TA.image_campaign_id = IC.id
WHERE <Your filters here>
LIMIT $start, $end
Hope this will help you.

How to search exact string using MySql Query which avoids extended values?

My Query looks like
$search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd
LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid
LEFT JOIN users ON nd.uid = users.uid
WHERE nd.status = 1 AND nd_rev.body LIKE LOWER('%node/100%')
AND nd.nid NOT IN(SELECT DISTINCT nid FROM term_node WHERE tid = 293)");
This query actually returns all the matches from node_revisions.body field, Which includes
node/1000, node/1001.... Etc.,
I want to get only the result of exact match where possible like
"node/100"
"node/100/"
"/node/100"
"/node/100/"
'node/100'
'node/100/'
'/node/100'
'/node/100/'
and not like
"node/1006"
"node/10064/"
"/node/1000"
"/node/10001/"
'node/10023'
'node/1005/'
'/node/1001'
'/node/10069/'
This above query returned me result which has string like below..
..a href="/node/1006"
How to avoid this kind of errors? Please help..
Try removing the % after 100 so the search won't consider any digit after 100, like this:
LOWER('%node/100')
Then consider the following Regular Expression
Example:
`nd_rev.body` REGEXP "^/?node/100/?$"
Oh ya... I got an resolution for this.. I redefined my query like below and it gives me result as expected..
$search_query = db_query("SELECT nd.nid, users.name, nd.type FROM node as nd
LEFT JOIN node_revisions as nd_rev ON nd_rev.nid = nd.nid AND nd_rev.vid = nd.vid
LEFT JOIN users ON nd.uid = users.uid
WHERE nd.status = 1 AND nd_rev.body RLIKE '[[:<:]]" . $search_string . "[[:>:]]'
AND nd.nid NOT IN(SELECT DISTINCT nid FROM term_node WHERE tid = 293)");
Look at
nd_rev.body RLIKE '[[:<:]]" . $search_string . "[[:>:]]'
This is what i expected

Calling a function(on other db) from a view

Hi I am trying to execute the following query, with no luck:
SELECT AA.Id, AA.ObjId, AA.NsId, AA.statusId, AA.LCID, AA.Title, AA.MessageBody_ClearText, AA.MessageBody_HTMLText,
AA.File1, AA.File2, AA.File3, AA.Status, AA.name, AA.createdate, AA.updatedate, AA.boneid, AA.main, AA.Sort,
BB.ID AS Expr1, BB.MainIDNum, BB.MessageID, BB.Message1, BB.Message2, BB.Message3, BB.MessageDate,
BB.AttachmentGUID1, BB.AttachmentGUID2, CC.MessageID AS Expr2, CC.Identification, CC.Viewed, CC.Deleted, CC.Id AS Expr3,
AA.FileName1, AA.FileName2, AA.FileName3
FROM dbo.gnvw_ObjectsBones AS AA INNER JOIN
--- XXX.dbo.MESSAGES AS BB ON BB.MessageID = AA.ObjId LEFT OUTER JOIN ---
dbo.PersonalMessages AS CC ON CC.MessageID = BB.MessageID AND CC.Identification = BB.MainIDNum
The marked line need to be change to a function call, I have a function called 'GetMessages' that takes an
int 'input' and it''s has to be that one: 'CC.Identification', so I tried to replace it to be like this:
SELECT AA.Id, AA.ObjId, AA.NsId, AA.statusId, AA.LCID, AA.Title, AA.MessageBody_ClearText, AA.MessageBody_HTMLText,
AA.File1, AA.File2, AA.File3, AA.Status, AA.name, AA.createdate, AA.updatedate, AA.boneid, AA.main, AA.Sort,
BB.ID AS Expr1, BB.MainIDNum, BB.MessageID, BB.Message1, BB.Message2, BB.Message3, BB.MessageDate,
BB.AttachmentGUID1, BB.AttachmentGUID2, CC.MessageID AS Expr2, CC.Identification, CC.Viewed, CC.Deleted, CC.Id AS Expr3,
AA.FileName1, AA.FileName2, AA.FileName3
FROM dbo.gnvw_Data_PersonalMessages_ObjectsBones AS AA INNER JOIN
XXX.dbo.GetMessages(CC.Identification) AS BB ON BB.MessageID = AA.ObjId LEFT OUTER JOIN
dbo.PersonalMessages AS CC ON CC.MessageID = BB.MessageID AND CC.Identification = BB.MainIDNum
I also tried other solutions but none of them worked, Does somebody here see the problem?
This is the errors that i get from running that 'solution':
'The multi-part identifier "CC.Identification" could not be bound.'
and,
'Invalid column name 'ID'.'
SQL is not my strong side, I'll be happy to hear any solutions, Hope I explained it right.
When you need to join table-valued function , use CROSS APPLY/OUTER APPLY instead of INNER/LEFT joins respectively.
...
FROM dbo.gnvw_Data_PersonalMessages_ObjectsBones AS AA
CROSS APPLY XXX.dbo.GetMessages(CC.Identification) AS BB
....
WHERE BB.MessageID = AA.ObjID
Update
I just noticed that join condition for dbo.AgamUsersPersonalMessages AS CC refers only to BB, and join condition for BB depends only on CC. That's incorrect, and you will still get the error. Without knowing what you want to get, I cannot give you a solution; you need to figure out join conditions yourself...