SQL Query to retrieve username on reference from a child table - mysql

I am working with MySQL. I have two tables, fb_data and fb_not.
Columns of first table are :
id
username
useremail
userpass
fbappid
fbapplink
fbuserid
Columns of second table are :
fk_id
liked_one
liker_one
The liked_one and liker_one columns are referencing fbuserid of fb_data table. Simply they are foreign keys. What I want to do is, to get the names of liker_one column which is in fb_not table. And I want to get the names from username column of fb_data table.
This demonstration shows how the query should work. I want to get the user name of each liker from the fb_data table.

You can get your desired output by inner joining fb_not to fb_data twice; once for liker_one and once for liked_one as below .
SELECT DISTINCT CONCAT (
t2.username
,'('
,t2.fbuserid
,') is the liker who liked '
,t3.username
,'('
,t3.fbuserid
,') post'
) AS Col1
FROM fb_not t1
INNER JOIN fb_data t2 ON t1.liker_one = t2.fbuserid
INNER JOIN fb_data t3 ON t1.liked_one = t3.fbuserid
distinct is used to remove duplicate rows.
Result:
Col1
----------------------------------------------------
nadeem(1234) is the liker who liked nadee(4321) post
You can check demo here

Simply join the table twice:
SELECT d1.username as [Liker], d2.username as [Liked]
FROM fb_not f
INNER JOIN fb_data d1
ON d1.fbuserid = f.liker_one
INNER JOIN fb_data d2
ON d2.fbuserid = f.liked_one

Here is your requested answer. Thanks Let me know if I can help more.
SELECT
username
FROM
fb_data fdata
JOIN
fb_not datan
ON fdata.fbuserid = datan.liker_one

Related

SQL select rows that have one value but not another

I have a table in SQL which will contain multiple rows for one id, as below
accountid Productname
1 GL
1 IP
1 MI
2 GL
2 IP
2 PA
3 MI
3 CP
3 IP
4 GL
4 CP
4 CI
I want to be able to select all accounts which have certain products but not other. For example all that have IP or GL but not MI, using the sample table above this would return accounts 2 and 4.
SELECT ccx_accountidname
FROM (
SELECT ccx_accountidname, ccx_productname
FROM Filteredccx_leadresearch
WHERE ccx_productname IN ('GL','IP')
AND ccx_accountidname IS NOT NULL
) AS T
WHERE ccx_productname NOT IN ('MI')
ORDER BY ccx_accountidname
and
SELECT DISTINCT LR1.ccx_accountidname
FROM Filteredccx_leadresearch LR1
LEFT JOIN Filteredccx_leadresearch LR2 ON LR1.ccx_accountid = LR2.ccx_accountid
AND LR2.ccx_productname IN ('GL', 'IP')
WHERE LR1.ccx_productname NOT IN ('MI')
AND LR1.ccx_accountidname IS NOT NULL
ORDER BY LR1.ccx_accountidname
Both give basically the same results, is there any way this can be done?
Thanks in advance for any help
Could you try this:
SELECT DISTINCT T1.Accountidname FROM TheTableThatContainsAccountnames as T1
JOIN AccountProductsTable as T2 on T1.AccountId=T2.AccountId
WHERE T2.ProductName = 'ProductYouWant'
AND T2.ProductName = 'AnOtherProductYouWant'
According to your post, all you really need is a simple query with the correct and logic. You want all accounts with Product name GL or IP but not in MI. This will do it without any other joins.
SELECT ccx_accountidname
FROM Filteredccx_leadresearch
WHERE
ccx_productname in ('GL','IP')
and ccx_productname not in ('MI')
EDIT
This will get you the account, though I doubt it will work in your overall solution. It's just hard to tell without seeing your complete dataset. This could be done with parameters too.
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
DROP TABLE #TempTable
IF OBJECT_ID('tempdb..#TempTableTwo') IS NOT NULL
DROP TABLE #TempTableTwo
create table #TempTable (accountid int, productname char(2))
insert into #TempTable (accountid,productname) values
(1,'GL'),
(1,'IP'),
(1,'MI'),
(2,'GL'),
(2,'IP'),
(2,'MA')
select distinct
t1.accountid,
1 as T
into #TempTableTwo
from
#TempTable t1
where
productname in ('GL','IP')
union all
select distinct
t1.accountid,
-1 as T
from
#TempTable t1
where
productname in ('MI')
select
accountid
from #TempTableTwo
group by accountid
having sum(T) > 0
I might be late for the game, but this should do the trick, if anyone is trying to solve a similar problem. I renamed your table and it's columns:
Filteredccx_leadresearch -> l_search
ccx_accountidname -> a_name
ccx_productname -> p_name
And here's the SQL:
(SELECT DISTINCT t1.a_name
FROM l_search t1
JOIN l_search t2 ON t1.a_name = t2.a_name
WHERE t1.p_name = 'IP'
OR t2.p_name = 'GL')
MINUS
(SELECT DISTINCT t1.a_name
FROM l_search t1
JOIN l_search t2 ON t1.a_name = t2.a_name
WHERE ((t1.p_name = 'IP'OR t1.p_name = 'GL') AND t2.p_name = 'MI')
OR
(t1.p_name = 'MI' AND (t1.p_name = 'IP' OR t1.p_name = 'GL')));
First set:
cross product of table on itself with same IDs, get account IDs which have a product 'IP' or 'GL'.
Second set:
cross product of table on itself with same IDs, get account IDs which have p_name ('IP' OR 'GL') on first cross property AND 'MI' on second.
Also, get those IDs, which have the same but the other way around: p_name 'MI' on first cross property AND ('IP' OR 'GL') on second.
And finally subtract the second from the first.
Here is a simple way to include the accounts that match either IP or GL and exclude those accounts if they have an record for MI without using a subquery.
This is assuming t1 is a table that has unique account numbers in accountid and t2 is the table you have shown above that has accountid and Productname columns.
SELECT DISTINCT
t1.accountid
FROM t1
LEFT JOIN t2 AS t2_match
ON t1.accountid = t2_match.accountid
AND
(
t2_match.Productname = 'IP'
OR t2_match.Productname = 'GL'
)
LEFT JOIN t2 AS t2_not_match
ON t1.accountid = t2_not_match.accountid
AND t2_not_match.Productname = 'MI'
WHERE
t2_match.accountid IS NOT NULL
AND t2_not_match.accountid IS NULL
This is really late, but it might help some one.
I'll focus only on using the columns we have on the table we are shown (won't combine it with other tables we were not given).
Since the only table in the example is not clearly named, I'll call it some_table
SELECT t.accountidname, t.productname
FROM some_table t
WHERE t.productname IN ('GL','IP')
AND t.accountidname NOT IN (
SELECT accountidname
FROM some_table
WHERE productname = 'MI'
);
The idea here is to:
Select all accountid and productname that have productname either GL or IP (3rd line)
Select all accountid that have a productname MI and remove them from the values we already have (4th line onwards)
With this values, filtering or combining it with other tables should be rather trivial.
You might want to replace the SELECT with SELECT DISTINCT if the combinations of accountid and productname could be repeated in the table.

Multiple joins on the same table

i have the following tables:
Technician
Tech_ID,First_Name,Last_Name
RT_QUEUE_Delta
Tech_ID, RT_Complete` (references a `Tech_ID` in `Technician`).
I need to get the data from a row in RT_Queue_Delta where RT_Completed = ?? but in my output I need to have the First_Name and Last_name that correlates with Tech_id and RT_Completed.
I can match one but I don't know how to match both. I tried:
select RTTech.First_Name as RT_First_Name,
RTTech.Last_Name as RT_Last_Name
from Technician as RTTech
Join RT_Queue_Delta as RT
on RT.RT_Completed = RTTech.Tech_ID
You can join to the Technician table multiple times:
select d.tech_id, t.first_name, t.last_name,
d.rt_completed as completed_id,
t2.first_name as completed_first_name,
t2.last_name as completed_last_name
from RT_QUEUE_Delta d
join Technician t on d.tech_id = t.tech_id
join Technician t2 on d.RT_Completed = t2.tech_id

SQL SELECT from 3 tables

ft_pupils
- id //Primary Key
- name
- start_date
ft_entries
- id
- pupil_id //Foreign Key
- aol_id
ft_aol
- id
- title
For every entry in the ft_entries table I want to use a SELECT to select every entry in the ft_entries table but with the aol_id replaced with the title inside of ft_aol.
I have managed to get:
SELECT name, aol_id FROM ft_pupils, ft_entries WHERE pupil_id = ft_pupils.id
to work fine.
I want the WHERE to be WHERE pupil_id = ft_pupils.id
I am so confused right now.
You can try this to get what you want by join 3 table.
SELECT Name,title FROM ft_entries
INNER JOIN ft_pupils ON pupil_id = ft_pupils.id
LEFT JOIN ft_aol ON ft_aol.id = aol_id
This will show you how to get the data you're looking for and display all the ids. You can remove the ids if you don't care to see them:
SELECT a.id,
b.pupil_id,
c.id,
a.NAME,
a.start_date,
c.title
FROM ft_pupils a
JOIN ft_entries b ON a.id = b.pupil_id
JOIN ft_aol c ON c.id = b.aol_id

better way of doing this SELECT in MySQL

Best way to do this SELECT?
I've got this tables:
t_department
id
name
t_users
id
name
type
*type can be:
1 SuperUser
2 normalUser
t_department_superuser
(A department can have many superUsers)
-idSuperUser
-idDepartment
t_superuser_normaluser
(A superUser can have many normalusers)
-idSuperUser
-idNormalUser
and finally
t_actions
-id (autonumeric)
-idUser (this can be an id of superUser or normalUser)
-action
Given a department name, for example "mainDepartment"
I need to get all records from t_actions of all normalusers and all superusers of that department
I have this, it works, but I am not an SQL expert (I am using MySQL) and I think it is not the best way to do the select, and t_actions is going to have loads of rows:
SELECT id,idUser,action
FROM t_actions
WHERE (idUser IN (
SELECT DISTINCT t_department_superuser.idSuperUser FROM t_department
RIGHT JOIN t_department_superuser ON t_department_superuser.idDepartment = t_department.id
LEFT JOIN t_superuser_normaluser ON t_superuser_normaluser.idSuperUser = t_department_superuser.idSuperUser
WHERE name='mainDepartment'
UNION ALL
SELECT DISTINCT t_superuser_normaluser.idNormalUser
FROM t_department
RIGHT JOIN t_department_superuser ON t_department_superuser.idDepartment = t_department.id
LEFT JOIN t_superuser_normaluser ON t_superuser_normaluser.idSuperUser = t_department_superuser.idSuperUser
WHERE name='mainDepartment')
ORDER BY id;
Any suggestions to make this better? thank you!!
because you are using left and right joins there will be null records, which is why you need the UNION... you can cut out the UNION with a simple null check
SELECT id, idUser, action
FROM t_actions
WHERE idUser IN
( SELECT DISTINCT COALESCE(tsn.idNormalUser, tds.idSuperUser)
FROM t_department td
RIGHT JOIN t_department_superuser tds ON tds.idDepartment = td.id
LEFT JOIN t_superuser_normaluser tsn ON tsn.idSuperUser = tds.idSuperUser
WHERE td.name='mainDepartment'
)
ORDER BY id;
note i also added alias's to your table names so its easer to write out and read the columns you are trying to select and join on.
EDIT
with the data the only possible way to do it with this table design is like this
SELECT id, idUser, action
FROM t_actions
WHERE idUser IN
((SELECT tds.idSuperUser
FROM t_department td
JOIN t_department_superusers tds ON tds.idDepartment = td.id
WHERE td.name='MAIN')
UNION
(SELECT tsn.idNormalUser
FROM t_department td
JOIN t_department_superusers tds ON tds.idDepartment = td.id
JOIN t_superuser_normaluser tsn ON tsn.idSuperUser = tds.idSuperUser
WHERE td.name='MAIN')
)
ORDER BY id;

How to Join 3 Tables in MySQL?

I am creating a view for my Database , I am joing 3 tables, Users,personal_info and contact_info, if you notice I have a lot of column names in my Select statement , since i don't want to include primary keys but it seems I have an error here, take a look
CREATE VIEW `payroll`.`new_view` AS
Select employee_id,employee_password,First_Name,Middle_Initial,
Last_Name,Date_Of_Birth,Beneficiaries,Home_Number,Address,Mobile_Number,Email_Address
From USER
LEFT JOIN personal_info on idUser = idPersonal_Info,
FULL JOIN contact_info on idUser = idContact_Info
The error is
ERROR 1146: Table 'payroll.full' doesn't exist
SQL Statement:
CREATE OR REPLACE VIEW `payroll`.`new_view` AS
Select employee_id,employee_password,First_Name,Middle_Initial,
Last_Name,Date_Of_Birth,Beneficiaries,Home_Number,Address,Mobile_Number,Email_Address
From USER
LEFT JOIN personal_info on idUser = idPersonal_Info,
FULL JOIN contact_info on idUser = idContact_Info
quote it with backtics: payroll.new_view
CREATE VIEW `payroll.new_view`
Error on:
LEFT JOIN personal_info on idUser = idPersonal_Info
you need to specify which column on which table equals which one on the other table, like
SELECT a,b,c from table1
LEFT JOIN table2
on table1.a= table2.columnY
in your case:
on USER.idUser = Personal_Info.idPersonalInfo
and the same for the 3rd Join
Another thing is the Comma at the end of the line:
LEFT JOIN personal_info on idUser = idPersonal_Info ,
it doesnt belong there.