MS Access equivalent query - mysql

I'm attempting to write a query that I know is compatible with MySQL to MS Access. This is a programming assignment, so I'm not expecting an answer straight up given to me, but I don't know MS Access' version of SQL well enough. I wrote the MySQL myself, and tested it to be working. That's when I realized that the query needed to work for MS Access instead. So here is the known code:
SELECT `D`.`RENT_NUM`,
`R`.`RENT_DATE`,
`D`.`VID_NUM`,
`M`.`MOVIE_TITLE`,
`D`.`DETAIL_DUEDATE`,
`D`.`DETAIL_RETURNDATE`,
`D`.`DETAIL_FEE`,
`D`.`DETAIL_RETURNDATE` - `D`.`DETAIL_DUEDATE` AS `DAYS_LATE`
FROM `detailrental` AS `D`
JOIN `rental` AS `R` ON `D`.`RENT_NUM` = `R`.`RENT_NUM`
JOIN `video` AS `V` ON `D`.`VID_NUM` = `V`.`VID_NUM`
JOIN `movie` AS `M` ON `V`.`MOVIE_NUM` = `M`.`MOVIE_NUM`
WHERE `D`.`DETAIL_RETURNDATE` - `D`.`DETAIL_DUEDATE` > 0
ORDER BY `R`.`RENT_NUM`, `M`.`MOVIE_TITLE`;
I've been attempting to convert to MS Access SQL, but I still don't get it. Here is the most recent attempt.
SELECT [D].[RENT_NUM],
[R].[RENT_DATE],
[D].[VID_NUM],
[M].[MOVIE_TITLE],
[D].[DETAIL_DUEDATE],
[D].[DETAIL_RETURNDATE],
[D].[DETAIL_FEE],
[D].[DETAIL_RETURNDATE] - [D].[DETAIL_DUEDATE] AS [DAYS_LATE]
FROM [DETAILRENTAL] AS [D] INNER JOIN
(
[RENTAL] AS [R] INNER JOIN
(
[VIDEO] AS [V] INNER JOIN [MOVIE] AS [M] ON [V].[MOVIE_NUM] = [M].[MOVIE_NUM]
) ON [D].[VID_NUM] = [V].[VID_NUM]
) ON [D].[RENT_NUM] = [R].[RENT_NUM]
WHERE [D].[DETAIL_RETURNDATE] - [D].[DETAIL_DUEDATE] > 0
ORDER BY [R].[RENT_NUM], [M].[MOVIE_TITLE];
The error I receive is Syntax error in JOIN operation. I know what that means, but I don't know MS Access' SQL well enough to spot the error.

It has been a while since I had to write any access query, so I just went with syntax described by official documentation http://msdn.microsoft.com/en-us/library/office/bb208854(v=office.12).aspx. Figured out it had syntax error in it. So to make query work you have to wrap JOIN with parenthesis. But each ON statement still needs to be inside each set of parenthesis not on outside. This should do the trick.
SELECT [D].[RENT_NUM]
,[R].[RENT_DATE]
,[D].[VID_NUM]
,[M].[MOVIE_TITLE]
,[D].[DETAIL_DUEDATE]
,[D].[DETAIL_RETURNDATE]
,[D].[DETAIL_FEE]
,[D].[DETAIL_RETURNDATE] - [D].[DETAIL_DUEDATE] AS [DAYS_LATE]
FROM (
(
(
[detailrental] AS [D] )
INNER JOIN [rental] AS [R]
ON [D].[RENT_NUM] = [R].[RENT_NUM] )
INNER JOIN [video] AS [V]
ON D.VID_NUM = [V].[VID_NUM] )
INNER JOIN [movie] AS [M]
ON [V].[MOVIE_NUM] = [M].[MOVIE_NUM]
WHERE [D].[DETAIL_RETURNDATE] - [D].[DETAIL_DUEDATE] > 0
ORDER BY [R].[RENT_NUM]
,[M].[MOVIE_TITLE];

Since we know that the problem is with the JOINs let's start from the innermost set of parentheses and work outwards:
[VIDEO] AS [V]
INNER JOIN
[MOVIE] AS [M]
ON [V].[MOVIE_NUM] = [M].[MOVIE_NUM]
That looks fine. Let's move out one level:
[RENTAL] AS [R] INNER JOIN
(
[VIDEO] AS [V]
INNER JOIN
[MOVIE] AS [M]
ON [V].[MOVIE_NUM] = [M].[MOVIE_NUM]
)
ON [D].[VID_NUM] = [V].[VID_NUM]
This JOIN won't work. Can you see why?

Related

Query blocking entirely MySQL server

I try to a run a specific query. However, when I execute it, the MySQL server doesn't respond anymore.
There is approximately 30000 rows in the table base_contrats_actifs but I don't know if this is a problem.
Here is the query :
UPDATE
base_contrats_actifs a
SET
a.code_indice = (
SELECT
MAX(g.code_indice)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
),
a.flag_bailleur_locataire = (
SELECT
MAX(g.flag_bailleur_locataire)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
),
a.compte_client = (
SELECT
MAX(g.compte_client)
FROM
base_gid g
WHERE
a.num_version = g.num_version_contrat
)
Can you see if there is an error ? If not, is there any way to debug the query ?
I don't know exactly why your update is non performant, but given the number of correlated subqueries you have, I'm not surprised. Try rewriting it as an update join:
UPDATE base_contrats_actifs a
INNER JOIN
(
SELECT
num_version_contrat,
MAX(code_indice) AS max_code_indice,
MAX(flag_bailleur_locataire) AS max_flag_bailleur_locataire,
MAX(compte_client) AS max_compte_client
FROM base_gid
GROUP BY num_version_contrat
) g
ON a.num_version = g.num_version_contrat
SET
a.code_indice = g.max_code_indice,
a.flag_bailleur_locataire = g.max_flag_bailleur_locataire,
a.compte_client = g.max_compte_client;

Add join to SQL query

I need to add a join 'level' to a pre-existing SQL query... unfortunately I keep getting errors with this query. I'm proabably falling somewhere but I cannot understand how to fix it.
The original query is the following:
SELECT
noleggio.*,
nome AS convenzionato
FROM
anag_convenzionati
RIGHT JOIN (SELECT
noleggio.*, targa, dc_standard AS dcstandard
FROM
veicoli_contratti
RIGHT JOIN (SELECT
noleggio.*,
nome AS assicurazione_pagante
FROM
anag_assicurazioni
RIGHT JOIN (SELECT
fatt_sconto_noleggio,
fatt_prezzo_noleggio,
id AS idnoleggio,
numero,
serie,
id_convenzionato,
stato_noleggio,
modalita_noleggio,
conducente,
locatario,
locazione_in_proprio,
id_assicurazione_pagante,
id_veicolo,
giorni,
fatt_giorni_noleggio,
fatt_prezzo_totale_noleggio,
data_pagamento_cliente_a_convenzionato,
ore_manodopera,
IF(locazione_in_proprio = 1, conducente, locatario) AS cedente
FROM
noleggio_veicoli
WHERE
((data_cancellazione IS NULL) OR (data_cancellazione = ''))
) AS noleggio ON noleggio.id_assicurazione_pagante = anag_assicurazioni.id
) AS noleggio ON noleggio.id_veicolo = veicoli_contratti.id
) AS noleggio ON noleggio.id_convenzionato = anag_convenzionati.id;
I need to join the resulting table with moduli_ocr table in this way:
SELECT
noleggio.*
FROM
(//query//) AS noleggio
LEFT JOIN
moduli_ocr ON moduli_ocr.id_noleggio = noleggio.id;
Where //query// is the code above.
The error I got (running the query in MySQL Workbench is:
Error Code: 1054. Unknown column 'noleggio.id' in 'on clause'
BTW I'm not sure if I have to use RIGHT or LEFT join but I will check this once the query is properly 'running'.
Best regards.
It seems that you assign idnoleggio alias to the field "id". Try joining on
moduli_ocr.id_noleggio = noleggio.idnoleggio;

unknown class: Fixnum Rails MySQL query - inserting variable breaks my search

I had a query which was working just fine:
#schedule = Schedule.find(params[:id])
#schedule_tasks = ScheduleTask.select("s.*, t.*, t.*, d.*, st.*").from("schedule_tasks st").
joins("left join schedules s ON s.id = st.schedule_id").
joins("left join tasks t ON t.id = st.task_id").
joins("right join days d ON d.id = st.day_id").
order("d.number, t.name").
group_by{|d| d.number}
I had to refine my search to only schedule_tasks with a specific schedule_id, so I edited the second line to:
joins("left join schedules s ON s.id = st.schedule_id AND s.id = ?", #schedule.id).
This has cause the following error:
unknown class: Fixnum
The error goes away if I take out the group_by - but I need that, and I have tried hard coding in the number instead of #schedule.id and that does not work either, a google search does not reveal a lot of details on this error.
For anyone coming here from Google, I used plain string interpolation to fix this issue. This method is vulnerable to SQL Injection, so make sure you type check your variables before using them.
In this case I would do
#schedule_id = #schedule.id
.
.
.
joins("left join schedules s ON s.id = st.schedule_id AND s.id = #{#schedule_id}")
Rather than following learning_to_swim's answer, which as noted is at risk of SQL injection, couldn't you cast your #schedule_id to a string?
#tasks = ScheduleTask.joins("left join [...] s.id = ?", #schedule.id.to_s)

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.

MYSQL IF Function

I am using two joins on the same table for two different select statements. I am wanting to implement an IF function, due to the fact that the table may contain a zero, I am wanting to substitue the zero for the word 'None'
Here is my SQL that works:
SELECT
CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`) AS `AssignedTo`,
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
Here is my SQL with the IF function that does not work:
SELECT
IF(AssignedTo IS 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)),
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
You can use CASE statement in this case or if you want to use IF statement then your statement is wrong.
It should be:
SELECT
IF(AssignedTo = 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)) AS Result,
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
Check out this blog: http://timmurphy.org/2009/08/13/inline-if-and-case-statements-in-mysql/
I think you want ".. = 0", not "... IS 0". You use IS when comparing with NULL.