use subquery in inner join mysql - mysql

This is my query
SELECT CONCAT(`SM_Title`,' ',`SM_Full_Name`) AS NAME,
`RG_Date`,
`RG_Reg_No`,
`RG_Stu_ID`,
`SM_Tell_Mobile`,
`SM_Tel_Residance`,
`RG_Reg_Type`,
Default_Batch,
`RG_Status`,
`RG_Final_Fee`,
`RG_Total_Paid`,
(`RG_Final_Fee`-`RG_Total_Paid`) AS TOTALDUE,
SUM(`SI_Ins_Amount` - `SI_Paid_Amount`) AS AS_AT_APRIAL_END
INNER JOIN
(SELECT `SI_Ins_Amount`,
`SI_Reg_No`
FROM
`student_installments`
GROUP BY MONTHNAME(`SI_Due_Date`)) Z ON
Z.`SI_Reg_No` = `registrations`.`RG_Reg_No`
FROM `registrations`
LEFT JOIN `student_master` ON `student_master`.`SM_ID` = `registrations`.`RG_Stu_ID`
LEFT JOIN `student_installments` ON `student_installments`.`SI_Reg_No` = `registrations`.`RG_Reg_No`
WHERE (`RG_Reg_Type` LIKE '%HND%' OR `RG_Reg_Type` LIKE '%LMU%' )
AND `SI_Due_Date` <= '2014-04-30' GROUP BY `SI_Reg_No`
It gave me an error near
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Z LIMIT 0, 25' at line 1

SELECT
CONCAT(SM_Title,' ',SM_Full_Name) AS NAME,
RG_Date,
RG_Reg_No,
RG_Stu_ID,
SM_Tell_Mobile,
SM_Tel_Residance,
RG_Reg_Type,
Default_Batch,
RG_Status,
RG_Final_Fee,
RG_Total_Paid,
(RG_Final_Fee-RG_Total_Paid) AS TOTALDUE,
SUM(SI_Ins_Amount - SI_Paid_Amount) AS AS_AT_APRIAL_END
FROM registrations
INNER JOIN
(SELECT SI_Ins_Amount,SI_Reg_No
FROM student_installments
GROUP BY MONTHNAME(SI_Due_Date)) Z ON Z.SI_Reg_No = registrations.RG_Reg_No
LEFT JOIN student_master ON student_master.SM_ID = registrations.RG_Stu_ID
LEFT JOIN student_installments ON student_installments.SI_Reg_No = registrations.RG_Reg_No
WHERE (RG_Reg_Type LIKE '%HND%' OR RG_Reg_Type LIKE '%LMU%' )
AND SI_Due_Date <= '2014-04-30'
GROUP BY SI_Reg_No

I notice you have fogotten the left table or subselect that you want to join to the (SELECT SI_INs .....) and previous this I could see there is no from clause before join.
I hope this helps you
Regards

You are using from clause in wrong position it should be just after selection of your columns, you can use below query:
SELECT
CONCAT(SM_Title,' ',SM_Full_Name) AS NAME ,RG_Date,RG_Reg_No,RG_Stu_ID,SM_Tell_Mobile,SM_Tel_Residance,RG_Reg_Type,Default_Batch,RG_Status,RG_Final_Fee,RG_Total_Paid,(RG_Final_Fee-RG_Total_Paid) AS TOTALDUE, SUM(SI_Ins_Amount - SI_Paid_Amount) AS AS_AT_APRIAL_END
FROM registrations AS reg
JOIN
(SELECT
SI_Ins_Amount,SI_Reg_No
FROM student_installments
GROUP BY MONTHNAME(SI_Due_Date)) AS Z
ON Z.SI_Reg_No = reg.RG_Reg_No
LEFT JOIN student_master AS sm
ON sm.SM_ID = reg.RG_Stu_ID
LEFT JOIN student_installments AS si
ON si.SI_Reg_No = reg.RG_Reg_No
WHERE (RG_Reg_Type LIKE '%HND%' OR RG_Reg_Type LIKE '%LMU%' ) AND SI_Due_Date <= '2014-04-30'
GROUP BY SI_Reg_No;

In the part below, from keyword should go before the inner join:
FROM registrations
INNER JOIN
(SELECT SI_Ins_Amount,
SI_Reg_No
FROM student_installments
GROUP BY MONTHNAME(SI_Due_Date)
) Z
ON Z.SI_Reg_No = registrations.RG_Reg_No

Related

Errors While Using IF statement in sql query

I am trying to make a query, which returns tipo_id from a table, depending on the value of this I want to join with another table, for example if tipo_id is 1 I want to join with table called p_read if tipo_id i want to join tv_read
this is what I tried to do.
SELECT ec.id,ec.estado,fv.id,fv.num_factura,fv.importe,fv.iva,fv.total,fv.fecha_consumo_inicio,fv.fecha_consumo_fin,
fv.fecha_factura, fv.fichero, c.total, l.tipo_id, lp.id_consumo FROM aldroges8.factura_venta fv
INNER JOIN aldroges8.lectura l ON fv.id=l.facturaVenta_id
INNER JOIN aldroges8.factura_cobro fc ON fc.facturaventa_id = fv.id
INNER JOIN aldroges8.cobros c ON c.id=fc.cobros_id
INNER JOIN aldroges8.estado_cobros ec ON ec.id = c.estado
IF (l.tipo_id=1)
INNER JOIN aldroges8.lectura_potencia lp ON l.id=lp.id
ELSE IF (l.tipo_id =3)
INNER JOIN aldroges8.lectura_tv_gas lp ON lp.id=l.id
WHERE fv.factura_enviada=1 AND fv.suministro_id=:id_contrato ORDER BY fv.fecha_factura DESC;
But i am getting this error.
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (l.tipo_id==1)
INNER JOIN aldroges8.lectura_potencia lp ON l.id=lp.id
ELSE' at line 7
So I want to know if there is a way on doing this if staments on a query, or do I need to make another query with tipo_id, thanks in advance
SELECT ec.id,ec.estado,fv.id,fv.num_factura,fv.importe,fv.iva,fv.total,fv.fecha_consumo_inicio,fv.fecha_consumo_fin,
fv.fecha_factura, fv.fichero, c.total, l.tipo_id,
/* Used case when statement to get the required result in that column */
case when l.tipo_id=1 then lp_1.id_consumo
when l.tipo_id=3 then lp_3.id_consumo end as id_consumo
FROM aldroges8.factura_venta fv
INNER JOIN aldroges8.lectura l ON fv.id=l.facturaVenta_id
INNER JOIN aldroges8.factura_cobro fc ON fc.facturaventa_id = fv.id
INNER JOIN aldroges8.cobros c ON c.id=fc.cobros_id
INNER JOIN aldroges8.estado_cobros ec ON ec.id = c.estado
left join aldroges8.lectura_potencia lp_1 ON l.id=lp_1.id
left join aldroges8.lectura_tv_gas lp_3 ON lp_3.id=l.id
WHERE fv.factura_enviada=1 AND fv.suministro_id=:id_contrato ORDER BY fv.fecha_factura DESC;
I would write this with the condition in the on clause and then use coalesce() in the select:
SELECT ec.id, ec.estado, fv.id, fv.num_factura, fv.importe, fv.iva,
fv.total, fv.fecha_consumo_inicio, fv.fecha_consumo_fin,
fv.fecha_factura, fv.fichero, c.total, l.tipo_id,
coalesce(lp_1.id_conumo, lp_3.id_consumo) as id_consumo
FROM aldroges8.factura_venta fv INNER JOIN
aldroges8.lectura l
ON fv.id = l.facturaVenta_id INNER JOIN
aldroges8.factura_cobro fc
ON fc.facturaventa_id = fv.id INNER JOIN
aldroges8.cobros c
ON c.id = fc.cobros_id INNER JOIN
aldroges8.estado_cobros ec
ON ec.id = c.estado LEFT JOIN
aldroges8.lectura_potencia lp_1
ON l.id = lp_1.id AND l.tipo_id = 1 LEFT JOIN
aldroges8.lectura_tv_gas lp_3
ON lp_3.id = l.id AND l.tipo_id = 3
WHERE fv.factura_enviada = 1 AND
fv.suministro_id = :id_contrato
ORDER BY fv.fecha_factura DESC;
The difference between doing the comparison in the ON verses in a CASE expression may seem subtle, but it can be important.
If there are multiple matches in either table, then putting the condition in the SELECT will result in duplicate rows.

Merging code from two SQL queries

I am attempting to combine the contents of two separate (but very closely related) sql queries, but am finding it difficult to get something that doesn't return syntax errors.
The two queries that are currently working are
SELECT module.ModuleCode,
demonstrator.FK_Course,
slot.fk_ModuleCode,
programme.C_val,
Count(slotdemo.FK_Demonstrator) AS CountOfFK_Demonstrator
FROM programme
INNER JOIN (demonstrator
INNER JOIN (((module
INNER JOIN slot ON module.ModuleCode = slot.fk_ModuleCode))
INNER JOIN slotdemo ON slot.SlotNo = slotdemo.FK_SlotNo) ON demonstrator.StudentID = slotdemo.FK_Demonstrator) ON programme.COURSE = demonstrator.FK_Course
WHERE demonstrator.`undergraduate`=1
GROUP BY module.ModuleCode
and
SELECT week.Hour,
module.color,
module.moduleName,
module.num_ugdemos,
slot.fk_Room,
slot.fk_ModuleCode,
slottime.FK_Hour,
slottime.FK_SlotNo,
programme.C_val,
Count(slotdemo.FK_Demonstrator) AS CountOfFK_Demonstrator
FROM week
INNER JOIN ((programme
INNER JOIN ((module
INNER JOIN slot ON module.ModuleCode = slot.fk_ModuleCode)
INNER JOIN slottime ON slot.SlotNo = slottime.FK_SlotNo) ON programme.COURSE = module.FK_Course)
LEFT JOIN slotdemo ON slot.SlotNo = slotdemo.FK_SlotNo) ON week.Hour = slottime.FK_Hour
GROUP BY week.Hour,
module.ModuleCode,
module.moduleName,
module.color,
slot.SlotNo,
slot.fk_Room,
slottime.FK_Hour,
programme.C_val HAVING((programme.C_val)<9);
my preliminary attempt at combining the two is
SELECT
week.Hour,
module.color,
module.moduleName,
module.num_ugdemos,
slot.fk_Room,
slot.fk_ModuleCode,
slottime.FK_Hour,
slottime.FK_SlotNo,
programme.C_val,
Count(slotdemo.FK_Demonstrator) AS CountOfFK_Demonstrator
FROM
week
INNER JOIN
(
(
programme
INNER JOIN
(
demonstrator
INNER JOIN
(
(
(
module
INNER JOIN
slot
ON module.ModuleCode = slot.fk_ModuleCode
)
)
INNER JOIN
slotdemo
ON slot.SlotNo = slotdemo.FK_SlotNo
)
ON demonstrator.StudentID = slotdemo.FK_Demonstrator
)
ON programme.COURSE = demonstrator.FK_Course
)
ON week.Hour = slottime.FK_Hour
WHERE
demonstrator.`undergraduate`=1
GROUP BY week.Hour,
module.moduleName,
module.color,
slot.SlotNo,
slot.fk_ModuleCode,
slot.fk_Room,
slottime.FK_Hour,
programme.C_val
The error message, for what's it's worth (which is not much) is:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'ON week.Hour = slottime.FK_Hour WHERE
demonstrator.undergraduate=1 GROUP BY we' at line 17
I think you want to UNION Two datasets together. Just use the UNION operator:
(SELECT .... FROM t1)
UNION
(SELECT ... FROM t2)
Both selects should return the same columns, IF the names differ you can use AS to rename it.

Unknown field on INNER JOIN from multi databases

I have following sql statement:
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (g.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN master_hankoya.goods g
ON ha.WEBHINID = g.goods_id 
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
I using INNER JOIN on multi-database ,so that you can see sc and master_hankoya is difference databases
When I run it ,I get error :
Unknown column 'g.goods_id ' in 'on clause'
You can see g alias for table master_hankoya.goods,and goods_id is a column in this
I guess that I have problem with INNER JOIN
Please help me correct it
Update : I check again and take a silly problem ,have a special character in query make it failed to run
try this
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (g.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN
(select * from master_hankoya.goods ) g
ON ha.WEBHINID = g.goods_id
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
Don't use alias name for master_hankoya.goods like
INSERT INTO wk1_tbl (shohin_code, shohin_mei, variation_flag)
SELECT ha.HINCD, ha.HINNMA, if (master_hankoya.goods.goods_para_id IS NULL, 0, 1) AS variation
FROM ( SELECT KOSHINCD, count(HINCD) AS quatity
FROM sc.HINMTF
GROUP BY KOSHINCD ) AS group_set
INNER JOIN sc.HINMTA ha
ON ha.HINCD = group_set.KOSHINCD
INNER JOIN master_hankoya.goods
ON ha.WEBHINID = master_hankoya.goods.goods_id
WHERE ha.HINKB = '2' and ha.DATKB <> '9';
INNER JOIN sc.HINMTA ha
Change this line to:
INNER JOIN HINMTA AS ha
INNER JOIN master_hankoya.goods g
Change that line to
INNER JOIN goods AS g
The syntax for setting an alias for a table is:
table_name AS table_alias

How to write a select statement inside another select in SQL

Can anyone tell me what is wrong with this query?
it gives a syntax error near the 2nd select
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
looks like you are missing a comma after MAX(h.edition)
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
besides the comma, you are selecting two fields in your subquery
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT preview FROM title_history WHERE idtitle_history = MAX(h.idtitle_history)),
(SELECT [file] FROM title_history WHERE idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
Adding to bluefeet's answer, you may want to check for reserved words. "File" for example is a reserved word in sql server.
Alias it as a virtual table. Change something like
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder) as virtual_column_alias;
Check this out. Hope this will work.

Mysql query, select 2 databases with 4 tables + nested SELECT?

This is my current query:
$sel = "SELECT
db1t1.userid, db1t1.customer_id, db2t1.customers_id, db2t1.orders_id, db2t2.products_price
FROM
database1.table1 db1t1
LEFT JOIN database2.table1 db2t1 ON
db1t1.customer_id = db2t1.customers_id
LEFT JOIN database2.table2 db2t2 ON
db2t1.orders_id = db2t2.orders_id
WHERE db1t1.userid IN(
SELECT
l.userid, l.username, r.username, r.cus_id
FROM
database1.table3 l
LEFT JOIN database2.table4 r ON
l.username = r.username
WHERE r.cus_id = '1234'
)";
Error message:
Operand should contain 1 column(s)
The error occurred because that you returned a result with multiple columns to an IN clause.
Try this:
SELECT
`db1t1`.`userid`, `db1t1`.`customer_id`, `db2t1`.`customers_id`,
`db2t1`.`orders_id`, `db2t2`.`products_price`
FROM `database1`.`table1` AS `db1t1`
LEFT JOIN `database2`.`table1` AS `db2t1`
USING (`customers_id`)
LEFT JOIN `database2`.`table2` AS `db2t2`
USING (`orders_id`)
WHERE `db1t1`.`userid` IN (
SELECT `l`.`userid`
FROM `database1`.`table3` AS `l`
LEFT JOIN `database2`.`table4` AS `r`
USING (`username`)
WHERE `r`.`cus_id` = 1234
)
What are you trying to achieve ? Maybe we can find a better solution.
Also, I think that you should do an INNER JOIN instead of a LEFT JOIN in the subquery.