Dynamic table headers in Laravel Blade from MySQL pivot table - mysql

I have a dynamic MySQL query and I want to create a table based on the dynamic MySQL pivot table. I am using Laravel, and I have the query in a blade file instead of a controller. Below is the query.
How can I create a dynamic table, with dynamic headers (instead of static) ?
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(assessements.id = ''',
assessements.id,
''', marks.mark, NULL)) AS ',
replace(assessement_name, ' ', '')
)
) INTO #sql
from assessements INNER JOIN marks ON marks.assessement_id=assessements.id WHERE assessements.term_id=2;
SET #sql = CONCAT('SELECT student_subject_averages.student_average,
student_subject_averages.ca_average,
student_subject_averages.exam_mark,
subjects.subject_name,
subjects.subject_type,
subjects.id as subject_id,
users.name,
users.salutation,
users.lastname, ', #sql, ' from marks
INNER JOIN assessements ON assessements.id = marks.assessement_id
INNER JOIN teaching_loads ON teaching_loads.id = marks.teaching_load_id
INNER JOIN subjects ON subjects.id = teaching_loads.subject_id
INNER JOIN users ON users.id = marks.teacher_id
INNER JOIN student_subject_averages ON student_subject_averages.student_id = marks.student_id
WHERE marks.student_id = 1869 AND `assessements`.`term_id` = 2 AND marks.active=1 AND student_subject_averages.teaching_load_id=marks.teaching_load_id
GROUP BY
marks.student_id,student_subject_averages.student_id,
subjects.id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Related

Stored procedure for search that takes multiple values for a single column

I am building up a website and I am working on the search part of it at the moment, so what I am trying to do is create a stored procedure that I am able to call that returns the values that I need.
I have put this together so far, but this limits me to only being able to select for example one model_id. I want to be able to search for model_ids 1,2,3,4 (example).
I was thinking of adding the parameters in as a string like '1,2,3,4' then splitting them and adding it into a temp table then I could do something like -product_type_id IN (select * from p_product_type_id)
PROCEDURE `sp_advert_search_load`(
IN p_product_type_id varchar(255),
IN p_product_details_id INT,
IN p_advert_status_id INT,
IN p_advert_type_id INT,
IN p_manufacturer_id INT,
IN p_model_id INT,
IN p_mechanism_id INT,
IN p_calibre_id INT,
IN p_orientation_id INT,
IN p_chamber_type_id INT,
IN p_trigger_type_id INT,
IN p_condition_id INT,
IN p_barrel_type_id INT,
IN p_cased INT,
IN p_certificate_id INT ,
IN p_price_more_than FLOAT ,
IN p_price_less_than FLOAT)
BEGIN
SELECT * FROM all_information_without_images
WHERE (product_type_id IN (p_product_type_id) or p_product_type_id IS NULL)
and (product_details_id = p_product_details_id or p_product_details_id IS NULL)
and (advert_status_id = p_advert_status_id or p_advert_status_id IS NULL)
and (advert_type_id = p_advert_type_id or p_advert_type_id IS NULL)
and (manufacturer_id = p_manufacturer_id or p_manufacturer_id IS NULL)
and (model_id = p_model_id or p_model_id IS NULL)
and (mechanism_id = p_mechanism_id or p_mechanism_id IS NULL)
and (calibre_id = p_calibre_id or p_calibre_id IS NULL)
and (orientation_id = p_orientation_id or p_orientation_id IS NULL)
and (chamber_type_id = p_chamber_type_id or p_chamber_type_id IS NULL)
and (trigger_type_id = p_trigger_type_id or p_trigger_type_id IS NULL)
and (condition_id = p_condition_id or p_condition_id IS NULL)
and (barrel_type_id = p_barrel_type_id or p_barrel_type_id IS NULL)
and (cased = p_cased or p_cased IS NULL)
and (certificate_id = p_certificate_id or p_certificate_id IS NULL)
and (price >= p_price_more_than or p_price_more_than IS NULL)
and (price <= p_price_less_than or p_price_less_than IS NULL);
END
Is there a better way I could achieve this? I suspect creating the temp tables is going to slow everything down quite a lot. Any pointers would be very helpful.
Thanks,
Richard
I have tried to use a prepared statement:
PROCEDURE `sp_advert_search_load`(
IN p_product_type_id varchar(255),
BEGIN
set #sql = concat( 'SELECT * FROM all_information_without_images
WHERE (product_type_id IN (',p_product_type_id,'))
');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
But I am getting an error 1615 - Prepared statement needs to be re-prepared is might be worth noting that all_information_without_images is a view.
I was thinking about just adding my view code to the prepared statement but it is very long and I think it exceeds the max length.
I am running out of ideas here.
Hello for anyone that wants to know how I managed to do this here is the code below:
First I used a function to split strings like '1,2,3,4' and insert then into a temp table:
BEGIN
# Temp table variables
SET #tableName = 'tmpSplit';
SET #fieldName = 'variable';
# Dropping table
SET #sql := CONCAT('DROP TABLE IF EXISTS ', #tableName);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
# Creating table
SET #sql := CONCAT('CREATE TEMPORARY TABLE ', #tableName, ' (', #fieldName, ' VARCHAR(1000))');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
# Preparing toSplit
SET #vars := toSplit;
SET #vars := CONCAT("('", REPLACE(#vars, ",", "'),('"), "')");
# Inserting values
SET #sql := CONCAT('INSERT INTO ', #tableName, ' VALUES ', #vars);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
# Returning record set, or inserting into optional target
IF target IS NULL THEN
SET #sql := CONCAT('SELECT TRIM(`', #fieldName, '`) AS `', #fieldName, '` FROM ', #tableName);
ELSE
SET #sql := CONCAT('INSERT INTO ', target, ' SELECT TRIM(`', #fieldName, '`) FROM ', #tableName);
END IF;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Then the main store prod created a temp table then used the function to insert a varchar value into a temp table then
WHERE
CASE WHEN #product_type_id = ''
THEN information_view.product_type_id = information_view.product_type_id
ELSE information_view.product_type_id IN (select * from tm_product_type_id)end;
PROCEDURE `sp_advert_search_load`(
IN p_product_type_id varchar(255)
)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tm_product_type_id;
CREATE TEMPORARY TABLE tm_product_type_id (product_type_id int);
SET #product_type_id = ifnull(p_product_type_id,'');
CALL sp_split(#product_type_id,'tm_product_type_id');
SELECT * FROM ( SELECT
e.entity_id AS entity_id,
e.entity_type_id AS entity_type_id,
enty.entity_description AS entity_description,
e.title_id AS title_id,
t.title AS title,
e.first_name AS first_name,
e.last_name AS last_name,
e.street_line_1 AS street_line_1,
e.street_line_2 AS street_line_2,
e.street_line_3 AS street_line_3,
e.town AS town,
e.county AS county,
e.postcode AS postcode,
e.email AS email,
e.telephone AS telephone,
e.company_name AS company_name,
e.company_desc AS company_desc,
e.website AS website,
e.concent AS concent,
e.longi AS longitude,
e.lati AS latitude,
a.advert_id AS ad_advert_id,
a.title AS ad_title,
a.advert_id AS advert_id,
a.description AS advert_description,
a.advert_status_id AS advert_status_id,
ads.description AS ad_statid,
a.advert_type_id AS advert_type_id,
avt.description AS ad_type,
a.product_details_id AS product_details_id,
a.price AS price,
a.created AS created_date,
pd.product_description AS product_description,
pd.product_type_id AS product_type_id,
pt.description AS product_type_description,
g.gun_id AS gun_id,
g.manufacturer_id AS manufacturer_id,
mg.manufacturer AS manufacturer,
g.model_id AS model_id,
mo.model AS model,
g.mechanism_id AS mechanism_id,
mec.mechanism AS mechanism,
g.calibre_id AS calibre_id,
cal.calibre AS calibre,
g.orientation_id AS orientation_id,
org.orientation AS orientation,
g.chamber_type_id AS chamber_type_id,
cht.chamber_type AS chamber_description,
g.trigger_type_id AS trigger_type_id,
trgt.trigger_type AS trigger_description,
g.condition_id AS condition_id,
con.`condition` AS `condition`,
g.barrel_type_id AS barrel_type_id,
bart.barrel_type AS barrel_description,
g.cased_id AS cased_id,
c.cased AS cased,
g.barrel_length_inches_id AS barrel_length_inches_id,
bli.barrel_length_inches AS barrel_length_inches,
g.barrel_length_inches_fraction_id AS barrel_length_inches_fraction_id,
blif.barrel_length_inches_fraction AS barrel_length_inches_fraction,
g.stock_length_inches_id AS stock_length_inches_id,
sli.stock_length_inches AS stock_length_inches,
g.stock_length_inches_fraction_id AS stock_length_inches_fraction_id,
slif.stock_length_inches_fraction AS stock_length_inches_fraction,
wp.weight_pound_id AS weight_pound_id,
wp.weight_pound AS weight_pound,
wo.weight_ounce_id AS weight_ounce_id,
wo.weight_ounce AS weight_ounce,
g.choke_type_id AS choke_type_id,
chot.choke_type AS choke_type,
g.choke_type_2_id AS choke_type_2_id,
chot2.choke_type AS choke_type_2,
g.ejection_id AS ejection_id,
ejec.ejection AS ejection,
g.certificate_id AS certificate_id,
cert.certificate AS certificate,
g.serial_number AS serial_number,
g.stock_number AS stock_number,
a.url_data AS url_data,
op.optic_id AS optic_id,
op.product_details_id AS optic_product_details_id,
pdop.product_description AS optic_product_description,
op.optic_make_id AS optic_make_id,
om.optic_make AS optic_make,
op.optic_custom_make AS optic_custom_make,
op.optic_model_id AS optic_model_id,
omod.optic_model AS optic_model,
op.optic_custom_model AS optic_custom_model,
op.optic_magnification_id AS optic_magnification_id,
omag.optic_magnification AS optic_magnification,
op.optic_custom_magnification AS optic_custom_magnification,
op.condition_id AS optic_condition_id,
optcon.condition AS optic_condition,
equ.equipment_id AS equipment_id,
equ.equipment_type_id AS equipment_type_id,
equt.equipment_type AS equipment_type,
equ.equipment_make_id AS equipment_make_id,
equm.equipment_make AS equipment_make,
equ.equipment_custom_model AS equipment_custom_model,
equ.condition_id AS equipment_condition_id,
equc.condition AS equipment_condition,
opa.optic_make_id AS optic_advert_optic_make_id,
oma.optic_make AS optic_advert_optic_make,
opa.optic_custom_make AS optic_advert_custom_make,
opa.optic_model_id AS optic_advert_model_id,
omoda.optic_model AS optic_advert_model,
opa.optic_custom_model AS optic_advert_custom_model,
opa.optic_magnification_id AS optic_advert_magnification_id,
omaga.optic_magnification AS optic_advert_magnification,
opa.optic_custom_magnification AS optic_advert_custom_magnification,
opa.condition_id AS optic_advert_condition_id,
optcona.condition AS optic_advert_condition,
img.image_id AS image_id,
img.image_src AS image_src
FROM
tbl_entity e
JOIN tbl_adverts a ON e.entity_id = a.entity_id
LEFT JOIN tbl_entity_type enty ON enty.entity_type_id = e.entity_type_id
LEFT JOIN tbl_title t ON t.title_id = e.title_id
LEFT JOIN tbl_guns g ON a.gun_id = g.gun_id
LEFT JOIN tbl_equipments equ ON a.equipment_id = equ.equipment_id
LEFT JOIN tbl_equipment_type equt ON equt.equipment_type_id = equ.equipment_type_id
LEFT JOIN tbl_equipment_make equm ON equm.equipment_make_id = equ.equipment_make_id
LEFT JOIN tbl_condition equc ON equc.condition_id = equ.condition_id
LEFT JOIN tbl_product_details pd ON a.product_details_id = pd.product_details_id AND a.product_type_id = pd.product_type_id
LEFT JOIN tbl_advert_type avt ON avt.advert_type_id = a.advert_type_id
LEFT JOIN tbl_advert_status ads ON ads.advert_status_id = a.advert_status_id
LEFT JOIN tbl_manufacturer mg ON g.manufacturer_id = mg.manufacturer_id AND mg.product_details_id = a.product_details_id
LEFT JOIN tbl_model mo ON g.product_details_id = mo.product_details_id AND mo.model_id = g.model_id
LEFT JOIN tbl_mechanism mec ON mec.product_details_id = g.product_details_id AND mec.mechanism_id = g.mechanism_id
LEFT JOIN tbl_calibre cal ON cal.product_details_id = g.product_details_id AND cal.calibre_id = g.calibre_id
LEFT JOIN tbl_barrel_type bart ON bart.product_details_id = g.product_details_id AND bart.barrel_type_id = g.barrel_type_id
LEFT JOIN tbl_chamber_type cht ON cht.product_details_id = g.product_details_id AND g.chamber_type_id = cht.chamber_type_id
LEFT JOIN tbl_trigger_type trgt ON trgt.product_details_id = g.product_details_id AND g.trigger_type_id = trgt.trigger_type_id
LEFT JOIN tbl_orientation org ON g.orientation_id = org.orientation_id
LEFT JOIN tbl_condition con ON g.condition_id = con.condition_id
LEFT JOIN tbl_cased c ON g.cased_id = c.cased_id
LEFT JOIN tbl_certificate cert ON cert.product_details_id = g.product_details_id AND cert.certificate_id = g.certificate_id
LEFT JOIN tbl_product_type pt ON a.product_type_id = pt.product_type_id
LEFT JOIN tbl_images img ON a.advert_id = img.advert_id AND img.primary_flag = 'Y'
LEFT JOIN tbl_stock_length_inches sli ON a.product_details_id = sli.product_details_id AND sli.stock_length_inches_id = g.stock_length_inches_id
LEFT JOIN tbl_stock_length_inches_fraction slif ON slif.stock_length_inches_fraction_id = g.stock_length_inches_fraction_id
LEFT JOIN tbl_barrel_length_inches bli ON a.product_details_id = bli.product_details_id AND bli.barrel_length_inches_id = g.barrel_length_inches_id
LEFT JOIN tbl_barrel_length_inches_fraction blif ON blif.barrel_length_inches_fraction_id = g.barrel_length_inches_fraction_id
LEFT JOIN tbl_choke_type chot ON a.product_details_id = chot.product_details_id AND chot.choke_type_id = g.choke_type_id
LEFT JOIN tbl_choke_type chot2 ON a.product_details_id = chot.product_details_id AND chot2.choke_type_id = g.choke_type_2_id
LEFT JOIN tbl_ejection ejec ON g.ejection_id = ejec.ejection_id
LEFT JOIN tbl_weight_pounds wp ON wp.weight_pound_id = g.weight_pound_id
LEFT JOIN tbl_weight_ounces wo ON wo.weight_ounce_id = g.weight_ounce_id
LEFT JOIN tbl_optics op ON op.optic_id = a.optic_id AND a.gun_id IS NOT NULL
LEFT JOIN tbl_product_details pdop ON pdop.product_details_id = op.product_details_id
LEFT JOIN tbl_optic_make om ON op.optic_make_id = om.optic_make_id AND op.product_details_id = om.product_details_id
LEFT JOIN tbl_optic_model omod ON op.optic_model_id = omod.optic_model_id AND omod.optic_make_id = om.optic_make_id
LEFT JOIN tbl_optic_magnification omag ON omag.optic_magnification_id = op.optic_magnification_id
LEFT JOIN tbl_condition optcon ON op.condition_id = optcon.condition_id
LEFT JOIN tbl_optics opa ON opa.optic_id = a.optic_id AND a.gun_id is null
LEFT JOIN tbl_product_details pdopa ON pdopa.product_details_id = opa.product_details_id
LEFT JOIN tbl_optic_make oma ON opa.optic_make_id = oma.optic_make_id AND opa.product_details_id = oma.product_details_id
LEFT JOIN tbl_optic_model omoda ON opa.optic_model_id = omoda.optic_model_id AND omoda.optic_make_id = oma.optic_make_id
LEFT JOIN tbl_optic_magnification omaga ON omaga.optic_magnification_id = opa.optic_magnification_id
LEFT JOIN tbl_condition optcona ON opa.condition_id = optcona.condition_id
ORDER BY
e.entity_id,
a.advert_id) information_view
WHERE
CASE WHEN #product_type_id = ''
THEN information_view.product_type_id = information_view.product_type_id
ELSE information_view.product_type_id IN (select * from tm_product_type_id)end;
END

MySQL Dynamic Pivot Table not giving proper results

I'm somewhat of a SQL rookie but I'm trying to write a pivot between three tables. I have the below query and it works perfectly aside from the MAX call. It causes my values that are less than the default value to be overridden. I have screenshots of my tables below. Any ideas on how to fix this?
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(cc.company_config_key_id = ', cck.id, ', cc.config_value, \'', cck.default, '\')) AS ', cck.company_config_key
)
) INTO #sql
FROM company_config cc
LEFT JOIN company_config_key cck
ON cck.id = cc.company_config_key_id;
SET #sql = CONCAT('SELECT co.id, co.name, ', #sql, ' FROM companies co LEFT JOIN company_config cc ON cc.company_id = co.id GROUP BY co.id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
companies:
company_config_key:
company_config:
Result (the secondary colors for companies 1 and 2 should be set):
It turns out I just had to set the internal if statement to NULL and then wrapped the max statement in an IFNULL.
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('IFNULL(MAX(IF(cc.company_config_key_id = ', cck.id, ', cc.config_value, NULL)), \'', cck.default, '\') AS ',cck.company_config_key)
) INTO #sql
FROM company_config cc
LEFT JOIN company_config_key cck
ON cck.id = cc.company_config_key_id;
SET #sql = CONCAT('SELECT co.id, co.name, ', #sql, ' FROM companies co LEFT JOIN company_config cc ON cc.company_id = co.id GROUP BY co.id');
SELECT #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;

MYSQL dynamic table name select with join and criteria

If I have this schema
lists (lead_id, list_id, campaign_id, ...)
campaign (campaign_id, ...)
custom_list_id (lead_id, ...)
there are many tables with name custom_list_id for various list_id s and I want to:
SELECT * from lists ls inner join campaign c ON c.id=ls.campaign_id
inner join custom_"#LISTID" cll ON ls.lead_id = cll.lead_id
How do I write this query?
thnx
Not sure what sql you really want, but try this:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'INNER JOIN custom_', list_id, 'cll', list_id, ' ON ls.lead_id = cll', list_id '.lead_id')
)
SEPARATOR ' '
) INTO #sql
FROM lists ;
SET #sql = CONCAT('SELECT * from lists ls inner join campaign c ON c.id=ls.campaign_id ', #sql);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Convert rows into columns in MySQL Query

I am getting above result from this query
SELECT sa.Student_Id,
CONCAT_WS(' ', es.Student_FName, es.Student_LName) AS Full_Name,
sa.Attendance_Date ,
sa.Attendance_Status
FROM student_attendance sa
INNER JOIN courses c
ON c.Course_Id = sa.Course_Id
INNER JOIN campus ca
ON ca.Campus_Id = c.Campus_Id
INNER JOIN students es
ON es.Student_Id = sa.Student_Id
WHERE sa.Course_Id = 1
ORDER BY sa.Attendance_Date DESC;
but i want this result
Can someone Do this for me Please..
select max(student|_id),full_name as student_FName ,
case attendance_date when attendance_date ='03-02-2016' and attendance_status =0
and full_name ='Shehriar Khan'
Then 'p' end as '3/1/2016',
case attendance_status when attendance_date ='03-01-2016'
and attendance_status =0 and full_name ='Ahtesham Illahi'
Then 'p' end as '3/2/2016'
from table_name
group_by full_name,attendance_date,attendance_stauts
Try like this
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(a.attendance_status = ''',
attendance_status,
''', IF(a.attendance_status = "1","P","X"), NULL)) AS "',
attendance_date,'"'
)
) INTO #sql
FROM student_attendance;
SET #sql = CONCAT('SELECT a.Student_ID,a.student_name,', #sql, '
FROM student_attendance a
LEFT JOIN student_attendance AS b
ON a.Student_ID=b.Student_ID GROUP BY a.Student_ID,b.Student_ID');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Fiddle link

MySQL Multiple Query > storing rows into columns

I need to create a SQL query that lists the following tables. Lines from the language list as column names. Thanks
Picture table and query:
If languages are known upfront
SELECT r.id, r.parent,
MAX(CASE WHEN n.language_id = 1 THEN n.name END) cs,
MAX(CASE WHEN n.language_id = 2 THEN n.name END) en
FROM cat_route r LEFT JOIN cat_route_name n
ON r.id = n.cat_route_id
GROUP BY r.id
Here is SQLFiddle demo
If you want it to be dynamic depending on what languages you defined in language
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT(
'MAX(CASE WHEN n.language_id = ', id, ' THEN n.name END) `', short, '`'))
INTO #sql
FROM language;
SET #sql = CONCAT(
'SELECT r.id, r.parent, ', #sql, '
FROM cat_route r LEFT JOIN cat_route_name n
ON r.id = n.cat_route_id
GROUP BY r.id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Here is SQLFiddle demo