How to merge SQL queries to use result first one? - mysql

I am trying to merge the below 2 MySQL statements to return just one result.
This first query returns a list of companyId's & name's:
SELECT gap.user_companies.companyId, gap.companies.name
FROM gap.user_companies
INNER JOIN gap.users
ON gap.user_companies.userId = gap.users.userId
INNER JOIN gap.companies
ON gap.user_companies.companyId = gap.companies.companyId
WHERE gap.users.username = 'tester';
The next query that I'm running returns a list of dates, but they need to use the companyId value from the above query.
Here is what I have so far:
SELECT creationdate, meetingdate FROM reports
WHERE reportId IN (
SELECT reportId FROM report_companies
WHERE companyId = 123
)
ORDER BY creationdate;
So I need to combine the above queries to return name from the COMPANIES table, as well as creationdate & meetingdate from the REPORTS table.
Belwo is some pseudo-code to help explain what the catch is:
The second query will need to use the companyId result of the first query.
The first query will return multiple records, so I need to update my WHERE companyId = 123 to something like
WHERE companyId IN (the companyId part of the first query's result)
Can someone please show how to merge these?

Related

Combine SQL query for userID with separate query for 2nd table

I'm trying to create an SQL query which filters information by customerID in one table and then combine that with information in another table. I have this query which filters by customerID
$query = mysqli_query($connection, "
SELECT *
FROM booked_activities
WHERE customerID LIKE $_SESSION[customerID]
");
/* INNER JOIN activities ON booked_activities.activityID = activities.activityID);*/
The second part I commented out is where I tried to combine the first half of the query with another table.
The activityID is a common ID in tables: booked_activites and activities.
Right now I can output the first query as activityID but I need to use the activityID to output the activityName from the activities table.
have you tried
$query = mysqli_query($connection, "SELECT *,ac.activityName FROM booked_activities INNER JOIN activities ac ON booked_activities.activityID = activities.activityID
WHERE customerID LIKE $_SESSION[customerID] );
also I would suggest using prepared statement for passing custometr id, instead of using sesstion variable directly in string.
SELECT * FROM booked_activities t1
join activities t2 on t2.activityID = t1.activityID
WHERE t1.customerID LIKE $_SESSION[customerID]

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.

MYSQL, Creating a view and pulling information from two tables

Okay so I have two tables:
hscust and hssales_rep
I need to create a view that shows me the reps fname and lname (as well as the customers) and show how much the customer is over on there credit balance.
This is the code I have:
CREATE VIEW OverLimit AS
SELECT
CONCAT(hssales_rep.last,hssales_rep.first) AS Rep,
CONCAT(hscust.last,hscust.first) AS Cust,
SUM(credit_limit - balance)
FROM hscust
INNER JOIN hssales_rep ON hscust.sales_rep = hssales_rep.repid
And it returns an empty result.
Any help is greatly appreciated!
salesrep table
cust table
A CREATE VIEW statement doesn't return a resultset.
A SELECT statement can return an empty resultset. But we'd expect the SELECT statement in your view definition to return either a single row, or throw an error.
I suggest you break this down a bit.
1) What problem is being solved by the CREATE VIEW statement. Why do you need a view?
2) Before you write a CREATE VIEW statement, first develop and test a SELECT statement that returns the required resultset. Do that before you put that into a view definition.
I also strongly recommend that you qualify all column references in the SELECT statement either with the table name or (preferably) a short table alias.
If you want to return a row for each Cust with an aggregate function (e.g. SUM) in your SELECT list, then add an appropriate GROUP BY clause to your SELECT statement.
It's not clear why we would want to use a SUM aggregate function.
The difference between "credit_limit" and "balance" would be the available (remaining) credit. A negative value would indicate the balance was "over" the credit limit.
SELECT CONCAT(r.last,r.first) AS Rep
, CONCAT(c.last,c.first) AS Cust
, c.credit_limit - c.balance AS available_credit
FROM hscust c
JOIN hssales_rep r
ON c.sales_rep=r.repid
ORDER
BY CONCAT(r.last,r.first)
, CONCAT(c.last,c.first)
, c.custid
If we only want to return rows for customers that are "over" their credit limit, we can add a WHERE clause.
SELECT CONCAT(r.last,r.first) AS Rep
, CONCAT(c.last,c.first) AS Cust
, c.credit_limit - c.balance AS available_credit
FROM hscust c
JOIN hssales_rep r
ON c.sales_rep=r.repid
WHERE c.credit_limit - c.balance < 0
ORDER
BY CONCAT(r.last,r.first)
, CONCAT(c.last,c.first)
, c.custid
Again, get a SELECT statement working (returning the required resultset) before you wrap it in a CREATE VIEW.

At most one record can be returned by this subquery

I am facing this error in my SQL select query. How can I fix this?
When I run this query and if there is only one record in HR_info table regarding my query then it show that result in combo box. If there are more than one record in this table then it show this error.
sSQL1 = "SELECT HR_Info.HR_ID,
(select hotel_name from hotel_info
where hotel_id = (select hotel_id
from hr_info
where hr_info.group_id = forms!pasenger_detail!group_id))
FROM HR_Info
WHERE (((HR_Info.Group_ID) = [forms]![Pasenger_Detail]![Group_ID]));"
here is the hotel_info talbe data
here is the hr_info table data
try TOP 1 or MAX / MIN on your sub subquery

Is it possible to combine MySQL queries to multiple tables into a single query based on the results from one of the queries?

The $userid of the currently logged in user is all the is currently available in the PHP code. I want to run a query against the mysql tables to return all of the status updates for myself and for friends ordered by createddate DESC.
MySQL Sample database tables:
[statusupdates]
statusupdateid int(8)
ownerid int(8)
message varchar(250)
createddate datetime
[friends]
friendid int(8)
requestfrom int(8)
requestto int(8)
daterequested datetime
dateupdated datetime
status varchar(1)
Question: Can I perform a single string query that returns each statusupdates.userid and the statusupdates.message ordered by statusupdates.createddate DESC?
Or do I have to run a query for each friends record where the $userid is in either the friends.requestfrom or friends.requestto then, run another query for alternate friends.requestfrom or friends.requestto (the one that doesn't include $userid), then sort all of the results by statusupdate.createddate and then get the statusupdates.message?
You want to look at MySQL Joins.
I think this may do something like what you're after, but it will almost definitely need debugging!
SELECT DISTINCT s.ownerid, s.message
FROM statusupdates s
LEFT JOIN friends f ON ($userid = f.requestfrom)
LEFT JOIN friends f ON ($userid = f.requestto)
ORDER BY s.createddate;
This is untested, but should work or at least get you in the right direction.
You could use IN() where you get a list of userids from a sub query. That subquery does a UNION on 2 queries - 1st to get the requestfrom userids, and 2nd to get the requestto userids. Finally we add an OR to include the current userid.
also, I assume that you also want to filter out where status = 1, as you don't want updates from those who have not confirmed friendships
SELECT s.ownerid, s.message
FROM statusupdates s
WHERE s.ownerid IN (
SELECT f1.requestfrom
FROM friends f1
WHERE f1.requestto = $userid
AND f1.status = 1
UNION
SELECT f2.requestto
FROM friends f2
WHERE f2.requestfrom = $userid
AND f2.status = 1
)
OR s.ownerid = $userid
ORDER BY s.createddate DESC
take a look at this sqlFiddle example - http://sqlfiddle.com/#!2/85ea0/3