From the question, it looks like what you have written quasi-resembles what Oracle calls an anonymous code block. MySQL does not facilitate such a mechanism.
With regard to what you want to accomplish, you do not need a stored procedure.
Try assembling the SQL statement like this:
@stmt = 'SELECT sid, ifnull(pricelist,"BASE"), count(*) AS recs FROM buyerList AS b ';
@stmt = CONCAT(@stmt,'LEFT JOIN sellerList AS s ON s.sid = b.sid AND s.pass = b.pass ');
@stmt = CONCAT(@stmt,'LEFT JOIN pricelists p ON ');
SELECT GROUP_CONCAT(CONCAT('(p.sid = a.sid AND p.preisliste = ',sid,' AND p.ean = a.ean AND p.iln = ',pricelist',)') SEPARATOR ' OR ')
INTO @LeftJoinClause FROM preislisten;
@stmt = CONCAT(@stmt,@LeftJoinClause,' WHERE b.bid = ?');
SELECT @stmt\G
This will print out the desired query
If it is the desired query, execute it
PREPARE sql FROM @stmt;
EXECUTE sql using @param_iln;
DEALLOCATE PREPARE sql;
Give it a Try !!!
If you actually want the query to be small without hardcoding every value just write the code with a more straightforward LEFT JOIN setup
SELECT p.sid, ifnull(p.pricelist,"BASE"), count(*) AS recs FROM buyerList AS b
LEFT JOIN sellerList AS s ON s.sid = b.sid AND s.pass = b.pass
LEFT JOIN pricelists p ON
(p.sid = a.sid AND p.preisliste = a.sid AND p.ean = a.ean)
WHERE b.bid = ?
GROUP BY p.sid,p.pricelist;
I also just noticed you have a.sid and a.ean, what table has an alias of a
?
I suggest you first read this question and answer Help with this query.
Then try to rewrite your queries using Option 3 (or all of the options). The following is a first attempt at option 1:
SELECT
p.id_pupil
, p.name
, p.surname
, ROUND(AVG(q.calificacion),2) AS average
, COUNT(DISTINCT q.id_qualification) AS count
, COUNT(DISTINCT CASE WHEN i.type_incident = 'miss' THEN i.id_incidents END)
AS misses
, COUNT(DISTINCT CASE WHEN i.type_incident = 'delay' THEN i.id_incidents END)
AS delays
, COUNT(DISTINCT CASE WHEN i.type_incident = 'attitude' THEN i.id_incidents END)
AS attitude
, COUNT(DISTINCT CASE WHEN i.type_incident = 'miss_justif' THEN i.id_incidents END)
AS misses_justificadas
FROM
pupils AS p
LEFT JOIN incidents AS i ON i.id_pupil = p.id_pupil
AND i.id_trimester = 1
LEFT JOIN qualifications AS q ON q.id_pupil = p.id_pupil
AND q.id_trimester = 1
AND q.type_qualification = 'class'
WHERE
p.level = 1
AND p.class = 'A'
AND p.id_trimester = 1
GROUP BY
p.id_pupil
, p.name
, p.surname ;
Best Answer
Instead of doing any
LEFT JOIN
, try this queryPROPOSED QUERY
SAMPLE DATA
When you execute it
you get this
PROPOSED QUERY EXECUTED
PROPOSED QUERY EXECUTED WITHOUT ROLLUP
GIVE IT A TRY !!!