I got a little problem and I wonder if there is a solution. Tried finding something existing, to no avail.
So here is my code :
Select
Order.AccountID,
Order.UserID,
Order.OrderID,
Order.OrderDate,
User.UserName,
Note.NoteID,
Note.UserID,
Note.NoteDate,
Note.Text
FROM
Order
INNER JOIN User ON (Order.UserID=User.UserID)
LEFT OUTER JOIN Note ON (Order.AccountID=Note.AccountID)
WHERE
Order.OrderDate >="2016-01-01"
AND
Order.OrderDate <= (current date -1 day)
AND
Note.NoteID IN (21,41,89)
AND
Note.NoteDate >="2016-01-01"
AND
Note.NoteDate<= (current date -1 day)
GROUPBY
Order.AccountID,
Order.UserID,
Order.OrderID,
Order.OrderDate,
User.UserName,
Note.UserID,
Note.NoteDate,
Note.Text
So we have 3 tables :
The Order Table : Contains Orders. They are saved with the userID who did the order.
The User Table : Has the UserIDs and the Username. I already used the table to link the usernames to the userIDs in the orders.
The Note Table : Contains notes on the account and the userID who wrote the note. I want to also get the usernames of the userIDS on the notes.
The one who did the order, is not necessary the one who wrote the note...
Question : How do I get the usernames Linked to my notes as they are already linked to my orders ?
Tables :
Order
AccountID | OrderID | OrderDate | UserID
User
UserID | Username
Note
NoteID | NoteDate | Text | UserID
Something like :
AccountID | OrderID | OrderDate | Order.UserID | Order.Username | NoteID | NoteDate | Text | UserID | Note.Username
How do ?
If I understand your question correctly, you just need to do the same as what you have already done with an alias:
Select
Order.AccountID,
Order.UserID,
Order.OrderID,
Order.OrderDate,
User.UserName,
Note.NoteID,
Note.UserID,
Note.NoteDate,
Note.Text,
NoteWriter.UserName as 'NoteWriter_Username'
FROM
INNER JOIN User ON (Order.UserID=User.UserID)
LEFT OUTER JOIN Note ON (Order.AccountID=Note.AccountID)
LEFT OUTER JOIN user NoteWriter on NoteWriter.userid = Note.userID
WHERE
Order.OrderDate >="2016-01-01"
AND Order.OrderDate <= (current date -1 day)
AND Note.NoteID IN (21,41,89)
AND Note.NoteDate >="2016-01-01"
AND Note.NoteDate<= (current date -1 day)
The trick is to alias the table you are joining on so that you can reference it. I've aliased the new join as NoteWriter, who will represent the user that added the note. I've also aliased the new column in your select, just to show you that you can name things a bit easier in your result set.
I've dropped the group by as it won't change anything. Unless you have some weird data, that is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.