MySQL duplicate names to be returned - mysql

I have a table with the following syntax:
| ID | institution_course1_id | institution_course2_id |
where application1_id and application2_id references to the same table. I need to get the values of both (so in other words I want to retrieve the name of each application)
I tried to join the tables but I am still only receiving 1 name in my results. Here is my SQL I use:
SELECT * FROM `client_applications`
LEFT JOIN `institution_courses` `name1`
ON `client_applications`.`institution_course1_id`=`name1`.`id`
LEFT JOIN `institution_courses` `name2`
ON `client_applications`.`institution_course2_id`=`name2`.`id`
WHERE `client_applications`.`client_id`=?
Is there a way for me to return in my results all rows from client_applications and then have 2 seperate added keys as "name1" and "name2" based on the above?

I am guessing that your problem is the application reading the results. Try putting in different aliases ("column names") for the two names:
SELECT ca.*, name1.name as name1, name2.name as name2
FROM `client_applications` ca LEFT JOIN
`institution_courses` `name1`
ON ca.`institution_course1_id` = `name1`.`id` LEFT JOIN
`institution_courses` `name2`
ON ca.`institution_course2_id` = `name2`.`id`
WHERE ca.`client_id` = ?;
Otherwise your query looks fine (although I added an alias for the first table as well).

try below:
SELECT ca.*, (select name1.name from name1 where ca.`institution_course1_id` = `name1`.`id`) as name1,(select name1.name from name1 where ca.`institution_course2_id` = `name1`.`id`) as name2
FROM `client_applications` ca
WHERE ca.`client_id` = ?;

Related

How do I add records which do not already exists in a table with an add query

I'd like the following add query to only add records which are not already in the table.
INSERT INTO tbl_TRUCK_train_cv ( handling, [text] )
SELECT qryTRUCK_CV_train_CW_2.cv_2 AS handling, "TRUCK: " & [tblTRUCKInformation].[fldTextTXT] & Chr(10) & Chr(13) & "train: " & [tbltrainInformation].[fldTextTXT] AS [text]
FROM (qryTRUCK_CV_train_CW_2 LEFT JOIN tbltrainInformation ON qryTRUCK_CV_train_CW_2.cw = tbltrainInformation.fldID) LEFT JOIN tblTRUCKInformation ON qryTRUCK_CV_train_CW_2.cv = tblTRUCKInformation.fldID
WHERE (((qryTRUCK_CV_train_CW_2.cv)<>""));
E.G.
The data in the table tbl_TRUCK_train_cv is as follows:
id | handling | text
-------------------------
"" | "CV1/CW1" | "bla"
"" | "CV4/CW7" | "bla"
The data in the add query is as follows:
id | handling | text
-------------------------
"" | "CV3/CW12" | "bla"
"" | "CV4/CW7" | "bla"
The add query should only add "" | "CV3/CW12" | "bla" as this records is not already in table tbl_TRUCK_train_cv
I have no clue how to solve this.
In this particular case the table is populated from different queries which might have duplicate values.
OK, this can be done in an Insert query similar to the one you have crafted in your question. Let me walk you through it one step at a time:
First, lets start with a query that joins the table and the query on the field '[handling]', it looks like this:
SELECT qryTRUCK_CV_train_CW_2.handling
FROM qryTRUCK_CV_train_CW_2 INNER JOIN
tbl_TRUCK_train_cv ON qryTRUCK_CV_train_CW_2.handling = tbl_TRUCK_train_cv.handling;
Now, you want a query that will find records in the query [qryTRUCK_CV_train_CW_2] that are NOT in the table [tbl_TRUCK_train_cv] . To do this, change the Join statement to be a LEFT JOIN. This will show all records in the query [qryTRUCK_CV_train_CW_2] regardless if there is a matching record in the table [tbl_TRUCK_train_cv].
SELECT qryTRUCK_CV_train_CW_2.handling
FROM qryTRUCK_CV_train_CW_2
LEFT JOIN tbl_TRUCK_train_cv ON qryTRUCK_CV_train_CW_2.handling =
tbl_TRUCK_train_cv.handling;
And finally, add the criteria WHERE [tbl_TRUCK_train_cv].handling Is Null.
SELECT qryTRUCK_CV_train_CW_2.handling
FROM qryTRUCK_CV_train_CW_2 LEFT JOIN tbl_TRUCK_train_cv ON
qryTRUCK_CV_train_CW_2.handling = tbl_TRUCK_train_cv.handling
WHERE (((tbl_TRUCK_train_cv.handling) Is Null));
This WHERE clause will limit the records to just ones that are in the Query but not in the table!
You are almost there.
Next, lets make this a grouping query in case there are duplicates in the field [handling] in the Query.
SELECT qryTRUCK_CV_train_CW_2.handling
FROM qryTRUCK_CV_train_CW_2 LEFT JOIN tbl_TRUCK_train_cv ON
qryTRUCK_CV_train_CW_2.handling = tbl_TRUCK_train_cv.handling
WHERE (((tbl_TRUCK_train_cv.handling) Is Null))
GROUP BY qryTRUCK_CV_train_CW_2.handling;
And finally, to take these results and insert them into the table [tbl_TRUCK_train_cv]
INSERT INTO tbl_TRUCK_train_cv ( handling )
SELECT qryTRUCK_CV_train_CW_2.handling
FROM qryTRUCK_CV_train_CW_2 LEFT JOIN tbl_TRUCK_train_cv ON
qryTRUCK_CV_train_CW_2.handling = tbl_TRUCK_train_cv.handling
WHERE (((tbl_TRUCK_train_cv.handling) Is Null))
GROUP BY qryTRUCK_CV_train_CW_2.handling;

return values of table 1 based on single column in table 2

I have 3 tables that I am using and need to make a query to return data from one table based on the value of a single column in the second table.
tbl_user
ID
login
pass
active
mscID
tbl_master
ID
name
training_date
MSCUnit
Active
tbl_msc
mscID
mscName
my current SQL statement:
SELECT
tbl_master.ID,
tbl_master.name,
tbl_master.training_date,
tbl_master.MSCUnit,
tbl_master.active,
tbl_user.mscID
FROM
tbl_master,
tbl_user
WHERE
tbl_master.active = 1 AND tbl_master.MSCUnit = tbl_user.mscID
The values stored in tbl_msc.mscID is a varchar(11) and it contains a string similar to A00 or A19. This is also the Primary key in the table.
The values stored in tbl_user.mscID matches that of tbl_msc.mscID. The values stored in tbl_master.UnitMSC also matches that of tbl_msc.mscID.
My goal is to return all records from tbl_master where the currently logged in user has the same mscID. The problem I am having is the statement returns all records in tbl_master.
I have tried several different join statements and for some reason, I cannot get this to filter correctly.
I am missing something. Any assistance in the SQL statement would be appreciated.
Thanks,
Will
You should be writing this using joins. I don't know how you know who the current user is, but the idea is to join the three tables together:
SELECT m.ID, m.name, m.training_date, m.MSCUnit, m.active,
u.mscID
FROM tbl_master m JOIN
tbl_user u
ON m.MSCUnit = u.mscID JOIN
tbl_msc msc
ON msc.mscID = u.msc_ID
WHERE m.active = 1 AND msc.mscName = ?;
Notice the use of proper, explicit, standard JOIN syntax and table aliases.
Select a.*, b.userid from
table_master a, table_user b where
a.mscunit in (select mscid from
table_user where active=1)
This should point you in the right direction.

SQL Update statement with 2 EXISTS clause

I am trying to update a value to be NULL where tracker_unique_id can be found in ab_split_tracker_unique_link where that ones ab_split_id can be found in a 3rd table ab_split_candidate.
I cant do it by giving it different values as they can be different from user to user on locals
UPDATE trustpilot_links SET `invite_after_enquiry` = NULL
WHERE EXISTS (
SELECT tracker_unique_id, ab_split_tracker_unique_link.ab_split_candidate_id
FROM ab_split_tracker_unique_link
WHERE EXISTS (
SELECT ab_split_candidate_id
FROM ab_split_candidate LEFT JOIN ab_split
ON ab_split_candidate.ab_split_id = ab_split.ab_split_id WHERE ab_split.reference="review_invite_after_enquiry"
)
);
Edit:
Table examples
Trustpilot Links
trustpilot_link_id | invite_after_enquiry | tracker_unique_id
1 1 123
2 0 1234
ab_split_tracker_unique_link
tracker_unique_id | ab_split_id
1234 32
Ab Split
ab_split_id | reference
32 review_invite_after_enquiry
I want to set values to null if there tracker cannot be found in table ab_split_tracker_unique_link with an ab_split_id that is equal to review_invite_after_enquiry in ab_split
Your subqueries are not related to their parent queries as they should be. Let's look at your inner-most query:
SELECT ab_split_candidate_id
FROM ab_split_candidate
LEFT JOIN ab_split ON ab_split_candidate.ab_split_id = ab_split.ab_split_id
WHERE ab_split.reference = 'review_invite_after_enquiry'
Well, first of all your WHERE clause dismisses outer-joined records, so this is essentially an INNER JOIN. But then: either there are such records or not. This has nothing to do with the record your are potentially updating, nor with the ab_split_tracker_unique_link you are looking up.
So either you are updating all records or none.
We would rather expect something like
UPDATE trustpilot_links tl
SET invite_after_enquiry = NULL
WHERE EXISTS
(
SELECT *
FROM ab_split_tracker_unique_link stul
WHERE stul.tracker_unique_id = tl.tracker_unique_id
AND ...
);
So add WHERE clauses that relate the subqueries to their parent queries.

mysql left outer join exclude

I have 2 tables 'conta' and 'details' and both the tables have null values and data in different case
conta
id col1 col2 col3 col4
1 Hi Bye See YOU
2 Hello (NULL) (NULL) (NULL)
details
id new_column1 new_column2 new_column3
1 bye see you
I want to apply join based on col2=new_column1 and col3 = new_column2 and col4 = new_column3 and get the values that are present in conta and not in details, so my output will be
conta
id col1 col2 col3 col4
2 hello (NULL) (NULL) (NULL)
But somehow i am unable to do so. I wrote below query, but its simply not resulting me the values i want.
SELECT `id`,`col1`,`col2`,`col3`,`col4` FROM `conta`
WHERE LOWER(`col2`) + LOWER(`col3`) + LOWER(`col4`) NOT IN (SELECT DISTINCT(LOWER(`new_column1`) + LOWER(`new_column2`) + LOWER(`new_column3`))
FROM `details`);
It simply give me no results! in the display
Any help?
Edit: I tried below query as suggested by #Uueerdo and it isn't giving me what i want.
SELECT conta.id,`col1`,`col2`,`col3`,`col4` FROM `conta`
LEFT OUTER JOIN `details`
ON ((conta.col2 IS NULL AND details.new_column1 IS NULL)
OR (LOWER(conta.col2) = LOWER(details.new_column1)))
AND ((conta.col3 IS NULL AND details.new_column2 IS NULL)
OR (LOWER(conta.col3) = LOWER(details.new_column2)))
AND ((conta.col4 IS NULL AND details.new_column3 IS NULL)
OR (LOWER(conta.col4) = LOWER(details.new_column3)))
WHERE details.id IS NULL
In the output in col2 i see a value 'Operations' which is also present in new_column1 in details table. This means it shouldn't be present in the output as i am trying to apply left outer join exclude I even tried using LEFT JOIN instead of LEFT OUTER JOIN and it isn't working either
Edit2: I found the solution. the query works and does the job. Exept that i had to run a command to replace all blank cells in the columns where i am applying join to NULL values.
You're better off using a SELECT .... FROM a LEFT JOIN b ON conditions WHERE b.id IS NULL style of query; null comparisons are a little different (and can be handled join conditions).
For example these evaluate to NULL, which is not true, which is false:
NULL = NULL
NULL IN (NULL)
But you can do things like this to compare nulls more easily:
ISNULL(a, x) = ISNULL(b, x)
(a IS NULL AND b IS NULL)
So you're join condition can be something like:
[...]
ON ((conta.col2 IS NULL AND details.new_column1 IS NULL)
OR (LOWER(conta.col2) = LOWER(details.new_column1)))
AND ((conta.col3 IS NULL AND details.new_column2 IS NULL)
OR (LOWER(conta.col3) = LOWER(details.new_column2)))
[and so on...]
WHERE details.id IS NULL
This assumes details has some sort of non-null row identification field that can used to reliably determine if there was a match or not.
Edit: The precise problem with your current query (aside from the null issues I previously outlined) is that + is not concatenation in MySQL, it is addition. With the data you've shown both LOWER(col2) + LOWER(col3) + LOWER(col4) and LOWER(new_column1) + LOWER(new_column2) + LOWER(new_column3) with yield 0 for the rows without NULL values in them. You would need to use the CONCAT() function to do the operation instead; but I'd discourage it because CONCAT('abc', 'def', '') is equal to CONCAT('ab', 'cd', 'ef').
Sidenote: DISTINCT is not a function, the () will have no effect (other than that they would cause a problem if they contained more than one result field).
You can keep your general format, and the aforementioned null issues, by a simple change with this format : WHERE (a, b, c) IN (SELECT a, b, c FROM ....
You can do a left join, then test for a null in the 2nd table to find the rows in the first table that didn't match any rows in the 2nd table.
SELECT
a.`id`,
a.`col1`,
a.`col2`,
a.`col3`,
a.`col4`
FROM `conta` a
LEFT JOIN `details` b
ON a.`col2` like b.`new_column1`
AND a.`col3` like b.`new_column2`
AND a.`col4` like b.`new_column3`
WHERE b.`id` IS NULL
Your Problem Solution Is inner join your (contact table) with (details table)
and get (contact.*) All columns where Contact.col1 !=details.new_column1
here is a query
Select conta.* from conta inner join details on conta.col1!=details.new_column1
You Can And More Where column in inner join
You could use the EXISTS operator to create an anti-semi join. Please take a look at this link: https://www.techonthenet.com/mysql/exists.php
Example Query:
SELECT
id,
col1,
col2,
col3,
col4
FROM conta
WHERE NOT EXISTS (
SELECT 1
FROM details
WHERE conta.col2 LIKE details.new_column1
AND conta.col3 LIKE details.new_column2
AND conta.col4 LIKE details.new_column3
)

MySQL alias for SELECT * columns

I'm creating a view that is using data that comes from the same table twice. As a result, same column names appear twice.
Thus, i need to give aliases to these columns. If i were to do it, i'd write it as:
SELECT u.* as 'one_*', u2.* as 'two_*'
FROM users u
LEFT JOIN relationships r ON u.id=r.id_one
LEFT JOIN users u2 ON r.id_two=u2.id
But that doesn't work. Thanks for your help!
EDIT:
Here's the data i'm actually getting:
| id | name | id | name |
1 john 2 alex
Here's the data i'd like to get (while still using a SELECT u.*, u2.*):
| id | name | brother_id | brother_name |
1 john 2 alex
You can't use * with an alias. Aliases can be used for individual columns.
You'll have to alias each column instead..
So unfortunately, if you have a lot of columns, you'll need to go:
SELECT u.col1 AS u_col1
, u.col2 AS u_col2
, u.col3 AS u_col3
-- etc
, u2.col1 AS u2_col1
, u2.col2 AS u2_col2
, u2.col3 AS u2_col3
-- etc
FROM table1 AS u
-- INNER JOIN / LEFT OR RIGHT OUTER JOIN / ,
table2 AS u2
Try using a UNION query:
e.g.
select a.typeid, a.typename from MYTABLE a where a.typeid=3 UNION select a.typeid, a.typename from MYTABLE a where a.typeid=4
Can you not just use SELECT * and then in your code refer to u.field1 and u2.field2?
I know this is an old question but I recently had the problem and came up with a solution.
First query the table and get the names of the columns
ex.
"SHOW COLUMNS FROM $table_name"
then use a loop to concat a prefix to the column name
ex
foreach ($all_columns as $the_column){
$alias_select .= ', '.$table_name.'.'.$the_column['Field'].' alias_'.$the_column['Field'];
}
then just put this string into your query and you will get another set of values all with the prefix_column_name.
SELECT alias.* does certainly work in mysql >= 5.6