Reputation: 329
I currently have a search function and I need it to return values from a different table (if the value exists)
SELECT crm.lead_id,
crm.id,
url,
contact,
info,
status_id,
added,
last_edited,
callback_date,
user.user,
status.status,
crm_updates.status_info
FROM crm,
user,
status,
crm_updates
WHERE (url LIKE '%$search%'
OR contact LIKE '%$search%'
OR info LIKE '%$search%'
OR status_id LIKE '%$search%'
OR added LIKE '%$search%'
OR last_edited LIKE '%$search%'
OR callback_date LIKE '%$search%'
OR user.user LIKE '%$search%')
AND crm.lead_id = user.id
AND status.id = crm.status_id
AND crm_updates.crm_id = crm.id
I need the status_info from crm_updates and they're currently connected by crm_id (in crm_updates) and id (in crm)
Right now only the values that have a status_info are selected. I need all values to be selected and the status_info included if it exists.
Upvotes: 3
Views: 1421
Reputation: 291
SELECT crm.lead_id, crm.id, url, contact, info, status_id, added, last_edited, callback_date, user.user, status.status, crm_updates.status_info
FROM crm
INNER JOIN user
ON crm.lead_id = user.id
INNER JOIN status
ON crm.status_id = status.id
LEFT JOIN crm_updates
ON crm.id = crm_updates.crm_id
WHERE url LIKE '%$search%'
OR contact LIKE '%$search%'
OR info LIKE '%$search%'
OR status_id LIKE '%$search%'
OR added LIKE '%$search%'
OR last_edited LIKE '%$search%'
OR callback_date LIKE '%$search%'
OR user.user LIKE '%$search%'
Use 'LEFT JOIN crm_updates': so if there is no record for crm_updates NULL will be returned.
Tip: Dont put join clauses in the where part of your query
Upvotes: 2
Reputation: 49
how about changing the line
AND status.id = crm.status_id
to
AND status.id =* crm.status_id
Upvotes: 0