SQL JOIN, Replace id with value - mysql

I have a query that is giving me trouble, im not sure how to do this
I have to retrieve records from a TICKETS table and join it together with 2 others,, That is not the problem, i need to replace one of the values in the record for a value in another table....
For Eg:
Table tickets:
numint
user_id
type
desc
attach
priority
status
date
assignation
Table users
numint
company_id
name
email
username
password
ps
security
token
date
Table companies
numint
name
Example Record
company_name - user_name - type - title - priority - status - date - assignation
"someCompany" - "someUser" - "someTitle" - 1 - "open" - "yyy/mm/dd" - 2(user_id)
in the assignation field of the returned record i need to replace it with the correspondant value from the users table IF it's NOT 0 (zero)
This is my Query so far
SELECT tickets.numint, tickets.type, tickets.title, tickets.description,
tickets.priority, tickets.status, tickets.date,
users.name AS user_name, companies.name AS company_name,
CASE WHEN tickets.assignation=0 THEN 'not-assigned'
ELSE ????????? END AS assignation
FROM tickets
LEFT JOIN users ON tickets.user_id = users.numint
LEFT JOIN companies ON users.company_id = companies.numint
i dont know how to replace that value, or if the CASE should after the joins...

Do you want to show username as assignation. use users.name in case.
SELECT tickets.numint, tickets.type, tickets.title, tickets.description,
tickets.priority, tickets.status, tickets.date,
users.name AS user_name, companies.name AS company_name,
CASE WHEN tickets.assignation=0 THEN 'not-assigned'
ELSE users1.name END AS assignation
FROM tickets
LEFT JOIN users ON tickets.user_id = users.numint
LEFT JOIN companies ON users.company_id = companies.numint
LEFT JOIN users AS users1 ON tickets.assignation = users1.numint

Related

SQL - LEFT JOIN multiple conditions - priority

I have 2 tables with a structure similar with this:
table: user
fields: id, active_office_address_id (this can be 0)
table: user_address
fields: id, user_id, type (home, office)
A user can have a "home" address (not mandatory) and multiple "office" addresses. I have a join to get a user address, but I want that if the user have a "home" address to get that address, not "office" address.
So, how can I get "home" address if exists, and only if that not exists to get "office" address. (In reality the query is much more complicated and the join is done on 4-5 tables)
SELECT * FROM user LEFT JOIN user_address ON (user.id = address.user_id AND
(user_address.type = "home" OR user.active_office_address_id = user_address.id))
group by user.id
You can use COALESCE() and join to your address table twice:
SELECT user.id
,COALESCE(home.address, office.address) AS Address
FROM user
LEFT JOIN user_address AS home
ON user.id = home.user_id
AND home.type = "home"
LEFT JOIN user_address AS office
ON user.active_office_address_id = office.user_id
GROUP BY user.id
Two left joins and a case statement will give you the address id you want.
SELECT user.*,CASE WHEN home_addr.id IS NOT NULL THEN home_addr.id ELSE ofc_addr.id END AS addr_id
FROM user
LEFT JOIN user_address AS home_addr
ON (user.id = home_addr.user_id AND home_addr.type = 'home')
LEFT JOIN user_address AS ofc_addr
ON (user.active_office_address_id = ofc_addr.id)
You could feed this back in as a sub-select for a particular user:
SELECT * FROM user LEFT JOIN user_address
WHERE user.id = ?
AND user_address.user_id = user.id
AND user_address.id IN
(SELECT CASE WHEN home_addr.id IS NOT NULL THEN home_addr.id ELSE ofc_addr.id END AS addr_id
FROM user
LEFT JOIN user_address AS home_addr
ON (user.id = home_addr.user_id AND home_addr.type = 'home')
LEFT JOIN user_address AS ofc_addr
ON (user.active_office_address_id = ofc_addr.id)
WHERE user.id = ?)
This assumes that only one home address exists per user.
At least in SQL Server, not sure about MySql, you can use a case statement in the order by clause, for example:
order by user.id, case user_address.type when 'home' then 1 else 2 end, --additional ordering clauses here

LIMIT Display of a different table field

Below are my tables:
1. tbluser
UserNumber - PK
Name
MemberType - Number
StationNumber - FK (connected to StationNo of tblStation)
2.tblStation
StationNo - PK
StationName
3.tblUserLogs
LogID - PK
UserID - FK (connected from UserNumber of tblusers)
LastLog
And all I want to do is to display Name (tblusers), StationName(tblStation) and LastLog(tblUserLogs) where MemberType is not equal to 1.
Here's my try...
SELECT tblusers.FirstName, tblstation.StationName, tblUserLogs.LastLog
FROM (tblstation INNER JOIN tblusers ON tblstation.StationNo = tblusers.StationNumber)
INNER JOIN tblUserLogs ON tblusers.UserNumber = tblUserLogs.UserID
WHERE (((tblusers.MemberType)<>1))
However, I get repeating records of my users. It displays ALL the LastLog data instead of showing the latest.
How should I do it?
Use this query:
SELECT tblusers.FirstName, tblstation.StationName, MAX(tblUserLogs.LastLog)
FROM (tblusers LEFT JOIN tblstation ON tblstation.StationNo = tblusers.StationNumber)
LEFT JOIN tblUserLogs ON tblusers.UserNumber = tblUserLogs.UserID
WHERE tblusers.MemberType != 1

MySQL Join two lists to check if a record exist

I've made an event system for my school that handles registrations for events.
Since we only want students to access sign up on the site, I've got a table called potentialusers. Every entry has a FullName and an Email.
When a user signs up on the site, the site checks if the student's email is in the potentialusers table, and if it is, the user is added to the users table.
I've also got a table called registrations. Whenever a user registers for an event, it's added to this table.
An entry looks like this: registrationid, eventid (foreign key to the event table), userid (also a foreign key to the user table, not the potentialusers).
I want to search for a name with a LIKE statement and get a result list of users, a column that states if the user is registered for the event and a column that states if the user is even registered at all.
This is what I've tried (I added some comments in curly brackets):
SELECT FullName, Email from potentialusers
LEFT OUTER JOIN registrations ON (potentialusers.Email = registrations...{1})
WHERE events.eventid = '7'{2} AND potentialusers.Email LIKE = '%jazerix%';
{1} -> Here is the first problem since, the registration table doesn't contains a email column, only a reference to the user in the usertable, which contains the email.
{2}-> Just so we can separate events, 7 is only an example.
In the end I want to return something like this:
Give this a try:
SELECT
p.FullName,
p.Email,
IF(u.userid IS NULL, 'False', 'True') RegisteredInSystem,
IF(r.registrationid IS NULL, 'False', 'True') RegisteredInEvent
FROM potentialusers p
LEFT JOIN users ON p.Email = u.useremail
LEFT JOIN registrations r ON r.userid = u.id AND r.eventid = 7
WHERE p.FullName LIKE '%jazerix%'
SELECT potentialusers.FullName, potentialusers.Email
, IF(users.userid IS NULL, 'False', 'True') Registered
, registration.registrationid
FROM potentialusers
LEFT JOIN users
ON potentialusers.Email = users. useremail
LEFT JOIN registrations
ON registrations.userid = users.id
WHERE potentialusers.Email LIKE '%jazerix%'
AND registrations.eventid = 7;
i think it should be like this
select
pus.fullname,
rg.email,
case (select count(*) from registrations where usr.id=foreignkey_connection_to_this_table)
when 0 then 'FALSE'
when 1 then 'TRUE'
else 'MULTIPLE REGISTRATIONS'
end as registered,
rg.id as registration_id
from potentialusers pus
join users usr using(foreign key connection to this table)
join event evt using(foreign key connection to this table)
join registrations rg using(foreign key connection to this table)
WHERE events.eventid = '7' AND potentialusers.Email LIKE = '%jazerix%';
i dont know your database model,so i white it in 'pseudo' sql.You must do some corections.

Fetching a result twice with deferend name

I have 1 table with tasks named opentask:columns: id,title,description,expires,creator_id,creator_name, executer_id, executer_name, priority_id, status_id1 table with users named user:
with columns: user_id, username
What I want is to create a query where there will be all columns from opentask table where the executer_id will be equal to the user_id of user table AND the creator_id will be equal to the user_id again. This creates a confusion because the first equality excludes the second.So I need somehow to create a query where I will include the usernames for the executer with something like where "opentask.executer_id=user_user_id" and at the same time I will include the username again (as a differend name?) for the creator with something like "where opentask.executer_id=user_user_id"So I try this, which of course I know that is missing something, can you help?
SELECT DISTINCT id, title, description, expires, creator_id, executer_id, oc_opentask.priority_id, oc_opentask.status_id, priority_name, status_name, user_id, username, (SELECT username FROM oc_opentask, oc_user WHERE oc_opentask.creator_id=oc_user.user_id) AS username2 FROM oc_opentask, oc_opentask_priority, oc_user, oc_opentask_status WHERE oc_opentask.priority_id=oc_opentask_priority.priority_id AND oc_opentask.executer_id=oc_user.user_id AND oc_opentask.status_id=oc_opentask_status.status_id ORDER BY oc_opentask.expires DESC
ReJOIN the table oc_user twice with different aliases creators and executers like so:
SELECT DISTINCT
t.*,
creators.user_name 'Creator name',
executers.username 'Executor name',
tp.priority_name,
s.status_name
FROM oc_opentask t
INNER JOIN oc_opentask_priority tp ON t.priority_id = tp.priority_id
INNER JOIN oc_user executers ON t.executer_id = executes.user_id
INNER JOIN oc_user creators ON t.creator_id = creators.user_id
INNER JOIN oc_opentask_status s ON t.status_id = s.status_id
ORDER BY t.expires DESC

How can I pull multiple user info from one query?

I have an invoice table that holds the id of the user that sent the invoice (from_id) and the user that received the invoice (to_id).
I want to be able to pull both of their info from the profile table but I am unable to figure out how.
Below is the query I'm running that let's me pull info for just one user (from_id) because of the join.
SELECT jobs.title, profiles.display_name, invoice.to_id, invoice.from_id, invoice.amount
FROM (invoice)
JOIN jobs ON jobs.job_id = invoice.job_id
JOIN profiles ON invoice.from_id = profiles.user_id
WHERE `invoice_id` = '3'
You can use the same table twice. Give them different aliased, which I think makes a query more readable anyway.
SELECT
j.title,
tp.display_name as to_name, fp.display_name as from_name,
i.to_id, i.from_id,
i.amount
FROM
invoice i
JOIN jobs j ON j.job_id = i.job_id
JOIN profiles fp ON i.from_id = fp.user_id
JOIN profiles tp ON i.to_id = tp.user_id
WHERE
i.invoice_id= '3'
You can join on a table more than once - in this case you need to join on the profiles table twice - once to get information about who the invoice is from and once to get the information about the user the invoice was sent to.
SELECT jobs.title
, Profile_From.display_name AS [From]
, Profile_To.display_name AS [To]
, invoice.to_id
, invoice.from_id
, invoice.amount
FROM invoice
JOIN jobs
ON jobs.job_id = invoice.job_id
JOIN profiles Profile_From
ON invoice.from_id = Profile_From.user_id
-- You are just missing this part
JOIN profiles Profile_To
ON invoice.to_id = Profile_To.user_id
WHERE invoice_id= '3'