Limits a left join? - mysql

Hi I have a query that pulls the results from a search but I want the left joined results to be limited to 1
Here is the left join:
LEFT JOIN #__ezrealty_siteplan AS sp ON sp.listing_id = a.id "
What I have tried
LEFT JOIN (SELECT * FROM jos_ezrealty LEFT JOIN jos_ezrealty_siteplan AS sp ON (sp.listing_id =jos_ezrealty.id ) LIMIT 1) AS sp ON (sp.listing_id=jos_ezrealty.id)
The entire query:
$query="SELECT a.*, cc.name AS category, ee.ezcity AS proploc, dd.name AS statename, bb.name AS countryname,
u.logo_image AS logo_image, u.mid AS mid, u.dealer_name AS dealer_name, u.dealer_company AS dealer_company,
u.dealer_phone AS dealer_phone, u.dealer_mobile AS dealer_mobile, u.published AS dealerpublished, sp.tenant AS tenant, sp.spacenum AS spacenum, sp.sf AS sf, sp.image AS tenantimage,
u.dealer_type AS dealer_type FROM #__ezrealty as a"
. "\n LEFT JOIN #__ezrealty_catg AS cc ON cc.id = a.cid"
. "\n LEFT JOIN #__ezrealty_locality AS ee ON ee.id = a.locid"
. "\n LEFT JOIN #__ezrealty_state AS dd ON dd.id = a.stid"
. "\n LEFT JOIN #__ezrealty_country AS bb ON bb.id = a.cnid"
. "\n LEFT JOIN #__ezrealty_profile AS u ON u.mid = a.owner"
. "\n LEFT JOIN #__ezrealty_siteplan AS sp ON sp.listing_id = a.id "
. "\n WHERE $extrastring AND a.published = '1' $vacant AND cc.access <= $my->gid $wheres "
. $order.' LIMIT '.$pageNav->limitstart.', '.$pageNav->limit;

In SQL Server, you could use CROSS APPLY. In other DBMS, you can use partitioning (windowing function ROW_NUMBER).
For MySQL, one solution is to use a subquery to get LIMIT 1, then join that to the table, e.g.
select a.col1, a.col2, a.col3, b.col1, b.col2
from
(
select a.col1, a.col2, a.col3, (select b.id as b_id from tbl_b b where b.a_id=a.id limit 1)
from tbl_a a
) a
left join tbl_b b on b.id=a.b_id

I thinks this will give you what you want
SELECT DISTINCT sp.id ,* FROM jos_ezrealty LEFT JOIN jos_ezrealty_siteplan AS sp ON sp.listing_id =jos_ezrealty.id

LEFT JOIN ( SELECT *
FROM #__ezrealty_siteplan
GROUP BY listing_id )
AS sp
ON sp.listing_id = a.id

Related

How not to include the ID in the result of the query when using Left Join

Im trying to populate my listview with data from three tables stu_tblbasicinfo,stu_tblfam and stu_tbleducbackground
they all have the same id which is TagID
Select A.TagID , A.Surname, A.Firstname, A.Middlename, A.Course, A.Year, B.ZipCode,
B.Province, B.Municipality, B.Barangay, A.ContactNo, A.EmailAddress, A.Birthdate,
A.Age, A.Birthplace, A.Religion, A.Gender, A.CivilStatus, A.Spouse, C.Mothersname,
C.M_occupation, C.M_Number, C.Fathersname, C.F_Occupation, C.F_Number,
C.GuardianName, C.G_Occupation, C.G_Number, D.Elementary, D.E_Years, D.JuniorHigh,
D.J_Years, Seniorhigh, D.S_Years
from stu_tblbasicinfo As A
left join stu_tblzipcode As B
on A.Barangay = B.Barangay
inner join stu_tblfam As C
ON A.TagID = C.TagID
inner join stu_tbleducbackground As D
ON A.TagID = D.TagID
My code works but the problem is it displays 3 TagID.
The result is like this
TagID(studentinfo table),Surname,Firstname,Middlename,TagID(familyBackground table),MName,FName,Gname,TagID(EducBackground table),Elementary,E_years,JuniorHigh,J_Years,SeniorHigh,S_Years
How can I make the result in this format?
TagID,Surname,Firstname,Middlename,Mname,Fname,Gname,Elementary,E.Years,JuniorHigh,J_Years,SeniorHigh,S_Years
Just this:
Select
A.TagID ,
A.Surname,
A.Firstname,
A.Middlename,
C.Mothersname,
C.Fathersname,
C.GuardianName,
D.Elementary,
D.E_Years,
D.JuniorHigh,
D.J_Years,
D.Seniorhigh,
D.S_Years
from stu_tblbasicinfo As A
left join stu_tblzipcode As B
on A.Barangay = B.Barangay
inner join stu_tblfam As C
ON A.TagID = C.TagID
inner join stu_tbleducbackground As D
ON A.TagID = D.TagID

Mysql triple join error:Not unique table/alias: 'cushbu_mark_user_favorites'

I have 3 tables in my db
1)cushbu_users (id,first_name,last_name)
2)cushbu_art (id,user_id(FK cushbu_user),title,base_price etc...) -for store user arts
3)cushbu_mark_user_favorites (id,user_id(FK cushbu_user),art_id(FK cushbu_art)) -for marking favourite items
I want to fetch the all art items of a particular user favourited
with count of favourites each art (stored in cushbu_mark_usier_favorites table )
Here is my query
SELECT
cushbu_art.id AS art_id,
cushbu_art.title,
cushbu_art.base_price,
cushbu_art.image_name,
CONCAT(
cushbu_users.first_name,
' ',
cushbu_users.last_name
) AS artist_name,COUNT(cushbu_mark_user_favorites.art_id)
FROM
cushbu_art
JOIN cushbu_mark_user_favorites ON cushbu_mark_user_favorites.art_id = cushbu_art.id
JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id
LEFT JOIN cushbu_mark_user_favorites ON cushbu_art.id=cushbu_mark_user_favorites.art_id
WHERE
cushbu_mark_user_favorites.user_id = 68
But i got Not unique table/alias: 'cushbu_mark_user_favorites' this join statement
LEFT JOIN cushbu_mark_user_favorites ON cushbu_art.id=cushbu_mark_user_favorites.art_id
UPDATE
SELECT
a.id AS art_id,
a.title,
a.base_price,
a.image_name,
CONCAT(
c.first_name,
' ',
c.last_name
) AS artist_name,COUNT(b.art_id)
FROM
cushbu_art a
JOIN cushbu_mark_user_favorites b ON b.art_id = a.id
JOIN cushbu_users c ON c.id = a.artist_id
LEFT JOIN b ON a.id=b.art_id
WHERE
b.user_id = 68
Try below query.
SELECT
cushbu_art.id AS art_id,
cushbu_art.title,
cushbu_art.image_name,
CONCAT(
cushbu_users.first_name,
' ',
cushbu_users.last_name
) AS artist_name , b.favorites_count as total_fav
FROM
cushbu_mark_user_favorites
LEFT JOIN cushbu_art ON cushbu_art.id=cushbu_mark_user_favorites.art_id
LEFT JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id
LEFT JOIN (SELECT art_id,count(*) as favorites_count FROM cushbu_mark_user_favorites GROUP BY art_id) as b ON b.art_id=cushbu_art.id
WHERE cushbu_mark_user_favorites.user_id=1
GROUP BY cushbu_art.id
Hope this will helpful to you.

Inner SELECT can't use `u.id` which is in outer SELECT

I have the following MySQL query:
SELECT
COUNT(b.`id`) AS todayOverdue,
DATE_FORMAT(t.`created_time`, "%Y%m%d") AS days
FROM
`Bill` b
LEFT JOIN `Order` o ON b.`order_id` = o.`id`
LEFT JOIN `Trade` t ON o.`trade_id` = t.`id`
LEFT JOIN `User` u ON b.`user_id` = u.`id`
WHERE
b. `deadline` <= "' . $todayTime . '"
AND b. `deadline` >= "' . $todayDate . '"
AND b.`is_paid` = 0
AND (
SELECT
COUNT(b2.`id`)
FROM
`Bill` b2
WHERE
b2.`deadline` <= "' . $todayTime . '"
AND b2.`user_id` = u.`id`
AND b2.`is_paid` = 0
OR (
b2.`deadline` <= b2.`paid_time`
AND b2.`is_paid` = 1
)
) < 2
GROUP BY
days
Why can't the inner SELECT use u.id which is in outer SELECT?
The inner select is completely independent of the outer select. The u table is being joined in the outer select in ways that are unknown to the inner select.
When you have
AND b2.`user_id` = u.`id`
Which row in u is being compared to which row in b2? The server has no way of knowing, so you need to define a table u2 and join it in the inner select.

bring the last 10 orders whitout repeating

I have the following query
SELECT a.id, a.fecha, a.ser, a.numero, c.nombre_apellido, a.estado, a.tipo, a.articulo, a.precio_asignado, a.retirada, a.pronta, a.precio, a.confirmada, d.marca, a.modelo, a.fecha_prometido, a.fecha_asignado, a.presupuesto, a.cant_llamados
FROM (
(
(
ordenes_servicio_bitacora b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
)
LEFT JOIN clientes c ON a.cliente_id = c.id
)
LEFT JOIN marcas d ON a.marca_id = d.id
)
ORDER BY b.id_bitacora DESC
LIMIT 10
and it brings me this
as you see the id column of the order is repeated because of the cross with bitacora table i need not to be repeated, any ideas? Thanks in advance.
DISTINCT should do the job in your case, as all the columns' data are repeated for the row not just the id column:
SELECT DISTINCT
a.id, a.fecha, a.ser, a.numero,
c.nombre_apellido, a.estado,
a.tipo, a.articulo, a.precio_asignado,
a.retirada, a.pronta, a.precio,
a.confirmada, d.marca, a.modelo,
a.fecha_prometido, a.fecha_asignado,
a.presupuesto, a.cant_llamados
FROM ordenes_servicio_bitacora b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
LEFT JOIN clientes c ON a.cliente_id = c.id
LEFT JOIN marcas d ON a.marca_id = d.id
ORDER BY b.id_bitacora DESC
LIMIT 10
SELECT a.id, a.fecha, a.ser, a.numero, c.nombre_apellido, a.estado, a.tipo, a.articulo, a.precio_asignado, a.retirada, a.pronta, a.precio, a.confirmada, d.marca, a.modelo, a.fecha_prometido, a.fecha_asignado, a.presupuesto, a.cant_llamados
FROM (
(
(
(SELECT DISTINCT id_orden
FROM `ordenes_servicio_bitacora`
ORDER BY id_bitacora DESC
LIMIT 10) b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
)
LEFT JOIN clientes c ON a.cliente_id = c.id
)
LEFT JOIN marcas d ON a.marca_id = d.id
)
i just made a subquery and the job is done, thanks by the answers and comments :)

Joining results of two independent query

I have two working queries:
1st returns the product list:
$sql = "
SELECT a.stockID, a.stockCatID, a.stockName, a.stockCode, a.stockCatCode,
CONCAT_WS(' » ', d.stockCatName, c.stockCatName, b.stockCatName) AS stockPath,
a.stockName AS stockTitle, a.stockID AS uniStock
FROM stockcards a
LEFT OUTER JOIN stockcategories b
ON a.stockCatID = b.stockCatID
LEFT OUTER JOIN stockcategories c
ON b.stockParentCat = c.stockCatID
LEFT OUTER JOIN stockcategories d
ON c.stockParentCat = d.stockCatID ";
2nd is basically returns the difference of total received and total sent whic is remaining quantity:
SELECT DISTINCT (COALESCE(o.totalReceived, 0) + COALESCE(p.totalSent, 0)) as RemainingStock
FROM deliverydetails k
INNER JOIN stockcards l ON k.stockID= l.stockID
LEFT JOIN
(
SELECT m.stockID, SUM(m.dQuantity) totalReceived
FROM deliverydetails m
WHERE m.dQuantity > 0
GROUP BY m.stockID
)
o ON k.stockID = o.stockID
LEFT JOIN
(
SELECT n.stockID, SUM(n.dQuantity) totalSent
FROM deliverydetails n
WHERE n.dQuantity < 0
GROUP BY n.stockID
)
p ON k.stockID = p.stockID
I need to add a new column to first query to display remanining quantity. But couldn't succeed to join this two. Thanks for any tip.
As it seems that your 2nd query just sums positive and negative dQuantities for each stockID, and then adds them together, I think this small change to your 1st query is
all that is needed:
SELECT a.stockID, a.stockCatID, a.stockName, a.stockCode, a.stockCatCode,
CONCAT_WS(' » ', d.stockCatName, c.stockCatName, b.stockCatName) AS stockPath,
a.stockName AS stockTitle, a.stockID AS uniStock,
dd.RemainingStock AS RemainingStock
FROM stockcards a
LEFT OUTER JOIN stockcategories b
ON a.stockCatID = b.stockCatID
LEFT OUTER JOIN stockcategories c
ON b.stockParentCat = c.stockCatID
LEFT OUTER JOIN stockcategories d
ON c.stockParentCat = d.stockCatID
LEFT OUTER JOIN
(SELECT stockID, SUM(dQuantity) AS RemainingStock
FROM deliverydetails
GROUP BY stockID) AS dd
ON dd.stockID = a.stockID