SELECT FROM 2 different tables using INNER JOIN - mysql

Last time I was able to combined 3 different SELECT queries since it was from the same table. Now, I'm trying to execute a query where in the info was from 2 different tables.
Here's my query string
SELECT applicantinfo.FirstName,
applicantinfo.MiddleName,
applicantinfo.LastName,
applicantaccess.ApplicantExamPassword
FROM applicantinfo
LEFT JOIN applicantaccess WHERE applicantaccess.ApplicantID = '" & lblID.Text & "'"
using myphpadmin to test this query and replacing the lblID.text with a value, Instead of showing up a singe result, it shows 2 rows.
Here's what it looks like
I think I miss used using the INNER JOIN keyword here.
My expected output should only be the first row.
*note
Jaranilla's ID should be '201458971' and password is 6zo93ie82m
lopez's ID should be '201437095' and password is 4ew93fo86t

You have to specify which properties constitute the join, assuming that "id" is the common attribute, e.g.
SELECT applicantinfo.FirstName, applicantaccess.ApplicantExamPassword FROM applicantinfo LEFT JOIN applicantaccess ON applicantinfo.id = applicantaccess.id;

In join put condition on which you want to join both tables, try following appID is you primary key and fk_appID is foregin key.
SELECT applicantinfo.FirstName, applicantinfo.MiddleName, applicantinfo.LastName, applicantaccess.ApplicantExamPassword
FROM applicantinfo as ainfo
LEFT JOIN applicantaccess as aa on ainfo.appID = aa.fk_appID
WHERE applicantaccess.ApplicantID = '" & lblID.Text & "'"

Related

DLookUp query to MySql

I am working on converting a legacy MS access system to a spring-boot application and I came across a big query. I am mostly done with converting the functions from access to mysql but not able to understand how to convert the following DLookUp sub-query as a mySql subquery
DLookUp("[price]","tbl_so","[so_id] = " & tbl_trade.so_id & " AND [product_id] = " & tbl_po.product_id
What I understood is following won't work as I don't have the Inner Joins set between the 3 tables, tbl_so, tbl_po, tbl_trade
SELECT tbl_so.price FROM tbl_so WHERE tbl_so.so_id = tbl_trade.so_id AND tbl_so.product_id = tbl_po.product_id
My question is how do I know how the tables will join with each other in this case and also when this DLookUp query is seldom used. And also the solution for this query.
Well, as a general rule, dlookup() can be replaced with a left join. However, you can also use a sub-query and they tend to be "less" change to the query.
So, if we had this:
SELECT id, partNum, dlookup("PartDescrt","tblParts","PartID = " & partNum)
as Description from tblOrders.
You would replace the above dlookup() with a sub-query like this:
SELECT id, partNum,
(select PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum)
AS Description
from tblOrders
The above is SQL or access sql syntax, but quite sure the same should work for MySQL.
If there is more then one partNumber that matches the above, then add a TOP 1, and a order by with some unique row (PK ID column is best). So the query becomes:
(select TOP 1 PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum
ORDER BY PartDescrt, ID DESC)
AS Description

VB.NET and MySQL query

How can i get values from mysql database usin while loop?
Sry for my bad english and i'm new in vb.net so please do not insult me because I do not know vb.net, I'm trying to learn, i'll try to explain what i need. :)
Lets go:
We know that EmailAddress is real email address, now first query must be something like this
Query1 = "select ID from database.table_users where email='" & EmailAddress & "'"
Now we know that Query1 will return value id from table_users.
Now we need create new query like this
Query2 = "select friend_id from database.table_friends where user_id='" & query1 & "'"
Okay, now Query2 return friend_id from table_friends.
One more query like this
Query3 = "select displayname from database.table_users where id='" & Query2 & "'"
Query3 must return displaynames of all users which we got in query2.
Example:
First i need query ID from table_users where email=EmailAddres
Then i need query friend_id from table_friends where user_id=ID
After that i nedd query displayname from table_users where id=friend_id
*these are just examples and they are not correct as you can see :D
I need 3 querys in while loop, and only last query (displayname) will go to the listbox. While must return all mysql values from table_friends where ID= id of EmailAddress user.
Join your tables into a single query. Something like this:
SELECT
Friends.displayname
FROM
table_users AS Users
INNER JOIN table_friends AS Connections
ON Users.user_id = Connections.user_id
INNER JOIN table_users AS Friends
ON Connections.friend_id = Friends.user_id
WHERE
Users.email = #EmailAddress
This creates two references to the table_users table, one for the initial user and one for the friends, connected by your many-to-many linking table. (Note also the use of a query parameter, which I highly recommend instead of directly concatenating input into the query.)
SQL is very powerful for querying structured data (hence its name), you'll be much better off building your query logic into SQL rather than keeping the SQL queries overly simple and making multiple trips to the database.
why loop and why can't you make it single query like below using JOIN
select tf.displayname from table_users tu
join table_friends tf on tu.id = tf.friend_id
and tu.email = '" & EmailAddress & "';

How do you format dates within MS Access Queries to prevent the US/UK issue

How do I ensure that I pick up the right number of records when filtering for dates within an Access Query:
SELECT ID, REF, SalesDate, DCount("ID","tblRecords"," Ref='" & [Ref] & "' AND [SalesDate]=#" & format([SalesDate],"yyyy/mm/dd") & "#") as EXPR1 from tblCurrent
It picks up the date ok if it cannot be misconstrued such as 28-04-12, but if it is 04-06-12 it doesn't pick it up as it's assuming it's the wrong way around.
Note that this query is not created on the fly or generated from a form etc...
I either use yyyy/mm/dd for dates in VBA:
#" & Format([SalesDate],"yyyy/mm/dd") & "#"
Or parameters, for building queries.
EDIT re additional information
Seeing you are using SQL server, I suggest you use a derived table, which you may find faster, for example:
SELECT dbo_Table_1.ADate, ACount FROM dbo_Table_1
LEFT JOIN (SELECT a.ADate,Count(*) As ACount
FROM dbo_Table_1 As a GROUP BY a.ADate) b
ON dbo_Table_1.Adate=b.ADate
EDIT re discussion
SELECT * FROM dbo_vwRecordsCurrent As t
LEFT JOIN (
SELECT a.OpptyIncentiveModifiedDate, a.DataSetID, Count(*) AS ACount
FROM dbo_vwRecordsHistorical AS a
WHERE a.OpportunityIgnored = True
GROUP BY a.OpptyIncentiveModifiedDate, a.DataSetID) AS h
ON t.OpptyIncentiveModifiedDate = h.OpptyIncentiveModifiedDate
AND t.DataSetID = h.DataSetID
I have aliased your tables as the names are very long, so to me, it is more readable to use aliases on the outer sql. They are essential in the inner sql. It is not a good idea to alias a derived table with the name of an existing table.

5 Tables -> Displaying Certain Distinct Rows

I'm pulling information that will eventually be from 5 tables at once based off of a filtering system. Right now I have three different databases running, its looking great. My issue is I have certain fields that I only want to display distinct information on and others i want to display all. To better explain I'm going to give my example.
My select code:
SELECT w.event,
w.city,
w.DATE,
a.TIME,
w.tmc,
a.weather,
a.surface_temperature,
p.top,
p.LEFT
FROM weather w
LEFT OUTER JOIN application a
ON a.DATE = w.DATE
AND a.tmc = w.tmc
LEFT OUTER JOIN pinlocations p
ON w.city = p.cityname
WHERE w.DATE = '" & datepicker_value.Text & "'
AND w.TIME LIKE '" & eventTime.SelectedItem.Value & "'
I have a map which I'm placing pins on based of the p.top and p.left. When I click on this I want to display the city name, the tmc, and then under that all the other information based off the filtered search. In the example above it creates pins on top of pins, making a new one for each field, I want it to be distinct.
I know the distinct command exists, just not sure how to use it in this situation.
Thanks!
Use a group by modifier, on the values you want to be distinct.
Then use a group_concat on the values you want to have listed in a comma-separated list.
SELECT group_concat(w.event) as events,
group_concat(w.city) as cities,
group_concat(w.`DATE`) as dates,
group_concat(a.`TIME`) as times,
group_concat(w.tmc) as tmcs,
group_concat(a.weather) as weathers,
group_concat(a.surface_temperature) as temperatures,
p.top,
p.LEFT
FROM weather w
LEFT OUTER JOIN application a
ON a.DATE = w.DATE
AND a.tmc = w.tmc
LEFT OUTER JOIN pinlocations p
ON w.city = p.cityname
WHERE w.DATE = '" & datepicker_value.Text & "'
AND w.TIME LIKE '" & eventTime.SelectedItem.Value & "'
GROUP BY p.top, p.left
If a left-top coordinate only ever links to one city (as you'd expect), there's no need to put it inside a group_concat statement. Nor does MySQL require* you to put it in the group by clause.
See:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
* ) you can force MySQL do enforce strict group by rules, but by default it is off.
You cannot use distinct here, because distinct is an all or nothing affair, it operates in the collectivity of all selected values, not just on one field.

How to join 1 table twice in the same query and keep results separate

we're building a scheduler system and have a couple of situations where we're trying to get some notes from a table to display. We've looked at other answers and none seem to quite match this problem.
The bookings table holds a numeric reference to both a client note (if present) and a stylist note (if present).
The notes table holds both client and stylist notes, each indexed by a unique numeric index
We've got our query working when we just want to read in the client notes:
SELECT bookings.bookingID, UNIX_TIMESTAMP(bookings.startDate) AS start_date, UNIX_TIMESTAMP(bookings.endDate) as end_date, clientDetails.firstName, clientDetails.lastName, clientDetails.phone1, clientDetails.phone2, clientDetails.email, services.name, services.serviceID, cNotes.note as client_notes, sNotes.note as stylist_note
FROM bookings
LEFT JOIN clientDetails ON bookings.clientID = clientDetails.clientID
LEFT JOIN services ON bookings.serviceID = services.serviceID
LEFT JOIN notes ON bookings.clientNotes = notes.notesID
WHERE bookings.startDate >= '" . $start_date . "' AND bookings.endDate <= '" . $end_date . "' AND bookings.stylistID = '" . $stylist_id . "'
ORDER BY bookings.startDate ASC;
Using this logic we can access the cient notes from the results array in php simply as: $results_array['note']
What we also want to be able to do is to get the stylist note for that booking as well, something like $results_array['stylist_note'].
How can we join the notes table again this time using:
LEFT JOIN notes ON bookings.stylistNotes = notes.notesID
BUT be able to reference these stylist notes separately from the client notes.
Thanks so much for any assistance.
You should be able to alias the table and columns:
SELECT ..., stylistnotes.note AS stylist_note
FROM ...
LEFT JOIN notes stylistnotes ON bookings.stylistNotes = stylistnotes.notesID