mysql Left join, mysql does an inner join? - mysql

I want to do a left join but mysql just does an inner join?
whats wrong with my query?
select av.*, ap.*
from tbl_available av
left join tbl_appointment ap
on av.avHours = ap.appointmenttime
where av.avCalendarId = 2
and (ap.calendarid = 2 or ap.calendarid= null)
and (ap.appointmentdate = "2012-10-01" or ap.appointmentdate = null)
and av.avDays = DayOfweek("2012-10-01")
order by avHours
mysql only gives those avHours who have a corresponding appointment
Thanks in advance!

Because of these conditions:
and ap.calendarid = 2
and ap.appointmentdate = "2012-10-01"
you only select rows from tbl_appointment which are not null.
If that's what you want - move them to the left join's ON part

Related

How can i Get Better Time Result on This Mysql Query

i am Using This Mysql Query and is working Good, But i need go get a Better Time result. How can i do it?
SELECT TblExistencias.id as ID, TblExistencias.codigo as Codigo,
TblPartes.detalle as Detalle,TblPartes.neto1 as PrecioActual,
TblExistencias.Condicion_Producto as Condicion,TblCategorias.categoria as Categoria,
TblSubcategorias.subcategoria as Subcategoria, TblExistencias.costo as Costo,
TblExistencias.serial as Serial, TblExistencias.vendido as Vendido,
TblConceptosFacturas.ventaonline as VentaOnline, TblRemitos.nroremitocompleto as Remito,
TblFacturas.nrofacturacompleto as Factura, TblFacturas.fecha as FechaVenta,
TblConceptosFacturas.ventaTotUn as Venta,TblConceptosFacturas.comisionmlunit as Comision,
TblFacturas.costoenvio as Envio, if(TblExistencias.vendido =1,
TblConceptosFacturas.ventaTotUn - TblExistencias.Costo - TblConceptosFacturas.comisionmlunit - TblFacturas.costoenvio,0) as Ganancia,
TblProveedores.razonsocial as Proveedor, TblFacturasCompras.nrofacturacompleto as Compra,
TblFacturasCompras.fecha as FechaCompra, TblClientes.razonsocial as Cliente
from TblExistencias
left join TblPartes on TblExistencias.codigo = TblPartes.codigo1
left join TblRemitos on TblExistencias.id_RemitoVenta = TblRemitos.id
left join TblFacturasCompras on TblExistencias.id_factura = TblFacturasCompras.id
left join TblClientes on TblRemitos.id_cliente = TblClientes.id
left join TblFacturas on TblRemitos.id_factura = TblFacturas.id
left join TblConceptosFacturas on TblFacturas.id=TblConceptosFacturas.id_factura and TblConceptosFacturas.codigoproducto = TblExistencias.codigo
left join TblCategorias on TblCategorias.id = TblPartes.id_categoria
left join TblSubcategorias on TblPartes.id_subcategoria = TblSubcategorias.id
left join TblProveedores on TblFacturasCompras.id_proveedor = TblProveedores.id
order by comision desc
The solution is create an index on each relational columns, like:
TblFacturasCompras.id_proveedor = TblProveedores.id
Problem was in order clause, Query passed from 87 Secs to 4 Secs. Thanks for help.

error subquery return more than 1 when doing multiple select

I want to do a multiple select in one query with different conditions. but somehow i'm stuck in this problem. any idea?
SELECT
(select io_link_event_names.name from doors left join controller_devices on doors.iid = controller_devices.iid left join events on controller_devices.mac = events.mac left join io_link_event_names on events.iolinkerid = io_link_event_names.extra where events.iolinkerid = "9000;1") AS forced,
(select doors.name FROM doors) AS doorname
ERROR #1242 - Subquery returns more than 1 row
consider this
SELECT d.[forced], doors.name as doorname
from doors
left join (
select controller_devices.iid, io_link_event_names.name as [forced]
from events
inner join controller_devices on controller_devices.mac = events.mac
inner join io_link_event_names on events.iolinkerid = io_link_event_names.extra
where events.iolinkerid = "9000;1"
) as d on d.iid = doors.iid
If you have more than 1 row in table doors, you get this error. If you want too see door name relevant to event selected in first query, use
select io_link_event_names.name,
doors.name doorname
from doors
left join controller_devices
on doors.iid = controller_devices.iid
left join events
on controller_devices.mac = events.mac
left join io_link_event_names
on events.iolinkerid = io_link_event_names.extra
where events.iolinkerid = "9000;1"

MySQL LEFT JOIN example with conditions

I am using following query to retrieve the needed objects:
SELECT *
FROM tb_po_items
LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material
LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service
WHERE po_id =47
Now I need to add following:
Condition 1 -> if tb_po_items.mos = 1 then LEFT JOIN tb_units ON tb_materials.material_unit = tb_units.id_unit
else
Condition 2 -> if tb_po_items.mos = 2 then LEFT JOIN tb_units ON tb_services.service_unit = tb_units.id_unit
How can I implement the use of both conditions in the MySQL query?
Thanks in advance.
Try this:
SELECT *
FROM tb_po_items
LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material
LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service
LEFT JOIN tb_units ON (
(tb_materials.material_unit = tb_units.id_unit AND tb_po_items.mos = 1)
OR
(tb_services.service_unit = tb_units.id_unit AND tb_po_items.mos = 2) )
WHERE po_id =47;
hi this is experimental so check before you go live.
SELECT * FROM tb_po_items
IF(tb_po_items.mos = 1, LEFT JOIN tb_materials ON tb_po_items.po_material = tb_materials.id_material, LEFT JOIN tb_services ON tb_po_items.po_service = tb_services.id_service)
WHERE po_id =47

SQL returns incorrect data using 2 left joins

I have written a MYSQL script, that returns incorrect data. I am quite fluent in SQL, but this query is not returning correct results. Can someone have a look and see whats going on. The problem is the noOfBids, and noOfRatedTimes. The values are the same for both columns and are large values too.
select
a.user_name as userName,
coalesce(count(b.sp_user_name),0) as noOfBids,
coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
coalesce(ROUND(AVG(d.user_rate),2),0)
from users a
left join project_imds b
on b.sp_user_name = a.user_name
left join projects c
on b.project_code = c.project_code
left join sp_user_rating d
on d.sp_user_name = b.sp_user_name
where a.user_type = 'SP'
and a.active = 'Y'
group by a.user_name
order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;
I have created a workaround on this, by creating a temp table to get the avg values and joining this to the main query.
Since I don't know the specifics of the data behind your query, this is only a guess. But perhaps you'd rather join "sp_user_rating" directly to "users", changing
left join sp_user_rating d
on d.sp_user_name = b.sp_user_name
to
left join sp_user_rating d
on d.sp_user_name = a.user_name
select
a.user_name as userName,
coalesce(count(b.sp_user_name),0) as noOfBids,
coalesce(ROUND(AVG(b.a_amount),2),0) as avgAmount,
coalesce(count(d.sp_user_name),0) as noOfRatedTimes,
coalesce(ROUND(AVG(d.user_rate),2),0)
from users as a
left join project_imds as b
on b.sp_user_name = a.user_name
left join projects as c
on b.project_code = c.project_code
left join sp_user_rating as d
on d.sp_user_name = b.sp_user_name
where a.user_type = 'SP'
and a.active = 'Y'
group by a.user_name
order by coalesce(ROUND(AVG(d.user_rate),2),0) desc;

i need to do an sql with if then else to join tables if the field is not null?

i need an sql stament that will give me something like this where if a field is null it doesn't do the join
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name FROM tbladmin,tblclients,tblgarages,tblapartments WHERE tblclients.ClientID =tbladmin.ClientID AND
IF (tbladmin.ApartmentID != null)
{
tblapartments.ApartmentID = tbladmin.ApartmentID
}
AND If(tbladmin.GarageID != Null)
{
tblgarges.GarageID = tbladmin.GarageID
}
Unless I'm missing something, this should just be an outer join.
SELECT
AdminID,
tblapartments.NameNo,
tblgarages.GarageID,
tblclients.Name
FROM
tbladmin INNER JOIN tblclients ON tbladmin.ClientID = tblclients.ClientID
LEFT OUTER JOIN tblgarages ON tbladmin.GarageID = tblgarages.GarageID
LEFT OUTER JOIN tblapartments ON tbladmin.ApartmentId = tblapartments.ApartmentID
You can use LEFT JOINs, when the joined column does not exist in the other table the result is a lot of NULL fields:
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name
FROM tbladmin
INNER JOIN tblclients
ON tbladmin.ClientID = tblclients.CliendID
LEFT JOIN tblgarages
ON tbladmin.GarageID = tblgarages.GarageID
LEFT JOIN tblapartments
ON tbladmin.ApartmentID = tblapartments.ApartmentID
I do not believe that this type of if logic is SQL standard. You could possibly implement it in a procedural SQL langauge like PL/SQL, plpgsql ... however to accomplish what you after i think a left join what you should look at.
SELECT AdminID,tblapartments.NameNo, tblgarages.GarageID, tblclients.Name
FROM tbladmin a
join tblclients b on b.ClientID = a.ClientID
left join tblapartments c on c.ApartmentID = a.ApartmentID
left join tblgarges d on d.GarageID = a.GarageID