Using Or in a sql statement which is operating in multiple tables - mysql

The Problem:
I have 2 tables i am selecting data from one called Table_Booked which contains one record with a Username and SessionID for each time a user books, another table called Table_Sessions which contains the Session details such as SessionId,Subject,TeacherID,Day,Am_Pm and WhatYear.
Im trying to select all the records from Table_Booked where the username is the same as the current users, and i also want to get the Day & Am_Pm data for each of the sessions the user has booked or the records for the session he is trying to book. The aim is to compare the records and if any occur in the same time slot not allow the user to book the session.
The Code:
Select Table_Session.Day,Table_Session.Am_Pm,Table_Session.SessionId
From Table_Session,Table_Booked
Where Table_Booked.Username = 'G9rpenman' and
((Table_Booked.SessionID = Table_Session.SessionId) Or (Table_Session.SessionId = 9))
When i run this code it fetches the information from Table_Session.SessionId = 9 twice and other tweaks have caused similarly random data selection. I cant find anything about this. Thank you for your help. If you feel i missed any crucial information out let me know and ill edit this.
Heres some screenshots of my tables with the data im using http://imgur.com/a/9fZtW

Simple rule: Never use commas in the FROM clause. Always use explicit JOIN syntax.
The reason for the duplication is the OR. I think this will do what you want:
Select s.Day, s.Am_Pm, s.SessionId
From Table_Booked b join
Table_Session s
on s.SessionID = b.SessionId or s.SessionId = 9
Where b.Username = 'G9rpenman' ;
If not, you may need union:
Select s.Day, s.Am_Pm, s.SessionId
From Table_Booked b join
Table_Session s
on s.SessionID = b.SessionId
Where b.Username = 'G9rpenman'
union
Select s.Day, s.Am_Pm, s.SessionId
from Table_Session s
where s.SessionId = 9;

Why don't you try a JOIN statement as opposed to selecting from both tables the way you are?
What's the output of the following query :
SELECT
TS.Day
,TS.Am_Pm
,TS.SessionId
FROM Table_Session TS
INNER JOIN Table_Booked TB ON TS.SessionId = TB.SessionID
OR TS.SessionId = 9
WHERE TB.Username = 'G9rpenman'
Could you post some sample data from both tables so we can see what you're trying to compare to provide more help?

Related

SQL query for Finding data with join or where within same table from multi tables

Im sorry i cant explain the question
I have a problem that i need to join 4 tables together to find some information. Im using inner join which is bringing me the right data but duplicate row having a minor change data. Lets say im getting this data
See the Table here
If we look at the results. At the last 4 rows we can notice simillar results. What i want to achieve is these 4 rows converted into 2.
I only want rows whose account id = vehicle account id and 110. I want these two rows. The join query i write is as follows
select Distinct vh.VehicleNo,jd.AccountID, tr.ID,jd.Memo,je.Description, jd.Cr,jd.Dr ,jd.Detail, je.JEntryId, je.ExpenseID from tbl_JDetail jd
inner join tbl_JEntry je on je.JEntryId = jd.JEntryID
inner join tbl_Trip tr on tr.ID = je.RefID
inner join tbl_Vehciles vh on vh.VID = tr.VehicleID
I really need to achieve this.. Any help would be appreciated how can i achieve. What i want is let me write the query in simple langauge
The query should first find rows in jdetail with accountid = 110. Then get its jentryid . Then in Jentry it should find the tripid and in trip table i have the vehicle id. Vehicle table contains vehicle id.
Then the query should find in jdetail with same jentryid and vehicleaccountid
i need jdetail accountid = 110 and accountid = vehicle.accountid
The vehicle relation is Jdetail > Jentry > Trip > Vehicle
i hope i was clear enough
Please add supporting information (create table statements, sample data, current output and desired output) to your question. As you have not included supporting information, I am unable to test this. This is my "best guess" based on your description.
select Distinct vh.VehicleNo,jd.AccountID, tr.ID,jd.Memo,je.Description, jd.Cr,jd.Dr ,jd.Detail, je.JEntryId, je.ExpenseID
from tbl_JDetail jd
inner join tbl_JEntry je
on je.JEntryId = jd.JEntryID
inner join tbl_Trip tr
on tr.ID = je.RefID
inner join tbl_Vehciles vh
on vh.VID = tr.VehicleID
and vh.AccountID = jd.AccountID
where jd.AccountID = 110
Solved it by using 2 CTEs. CTE1 finds the jentry_id of all records using account ID = 110
and CTE2 find all the required data with inner join cte on cte.JEntryId = jd.JEntryID
It solved all my problems..
Thankyou. Hope it help someone else too

How to use one table multiple times for inner join in SQL Server?

I am trying to make a table that includes join between 3 tables in the MSSS 2008. There is a fact table, a date table, and a course table. I should join them to make a base table. In date table there is a one parameter that name is Academic Year lookup, and the values in this parameter is like 2000/1, 2001/2. This parameter in the base table should separate to three parameter such as CensusYear, StartYear, and ApplicationYear. Therefore, I need the data table multiple times. I executed a inner join query, and already I have four inner join statement, but I am getting some extra years, and I'm losing some years. I believe, my query should be wrong somewhere.
The attached file is include the design view that created in the MS Access, it'll help to see the tables, and understand what I need to create.
[Design View in Ms Access][1]
SELECT
A.[EventCount],
B.[AcademicYearLookup] AS [CensusYear],
C.[AcademicYearLookup] AS [StartYear],
D.[AcademicYearLookup] AS [ApplicationYear],
B.[CurrentWeekComparisonFlag],
B.[AcademicWeekOfYear],
case
when A.[ApplicationCensusSK] = 1 then 'Same Year'
when A.[ApplicationCensusSK] = 2 then 'Next Year'
when A.[ApplicationCensusSK] = 5 then 'Last Year'
ELSE 'Other'
END as [CensusYearDescription],
B.[CurrentAcademicYear],
A.[StudentCodeBK],
A.[ApplicationSequenceNoBK],
A.[CourseSK],
A.[CourseGroupSK],
A.[CourseMoaSK],
A.[CboSK],
A.[CourseTaughtAbroadSK],
A.[ApplicationStatusSK],
A.[ApplicationFeeStatusSK],
A.[DecisionResponseSK],
A.[NationalityCountrySK],
A.[DomicileCountrySK],
A.[TargetRegionSK],
A.[InternationalSponsorSK] INTO dbo.[BaseTable3yrs]
FROM Student.FactApplicationSnapshot A
INNER JOIN Conformed.DimDate AS B ON A.[CensusDateSK] = B.[DateSK]
INNER JOIN Conformed.DimDate AS C ON A.[AcademicYearStartDateSK] = C.[DateSK]
INNER JOIN Conformed.DimDate AS D ON A.[ApplicationDateSK] = D.[DateSK]
INNER JOIN Student.DimCourse ON A.CourseSK = Student.DimCourse.CourseSK
WHERE (((B.CurrentAcademicYear) In (0,-1))
AND ((A.ApplicationCensusSK) In (1,2,5))
AND ((Student.DimCourse.DepartmentShortName)= 'TEACH ED'));
/* the query to check that the result it's correct or not, and I check it by academic week of year, and I found that I am lossing some data, and I have some extra data, means maybe join is wrong*/
select * from [BaseTable3yrs]
where [StudentCodeBK]= '26002423'
AND [ApplicationSequenceNoBK] = '0101'
order by [AcademicWeekOfYear]
When doing recursive joins like this, it's easy to get duplicate records. You could try gathering the Conformed data separately into a table variable and then joining to it. This would also make your query more readable.
You might also try a SELECT DISTINCT on your main query.

Inefficient Query

SELECT submissions.created_at, guests.accepted
FROM submission
INNER JOIN guests
ON guests.event_id = 1
ORDER BY submissions.created_at ASC;
Currently this query is taking a long time to run (may not even return everything).
What I am trying to accomplish:
Grab the field submissions.created at and guests.accepted (the two are linked by a submission_id)
given a certain event_id (event 1 for example).
What is wrong with my query?
You forgot to give the JOIN condition in your query. Try this:
SELECT submissions.created_at, guests.accepted
FROM submission s
INNER JOIN guests g on g.event_id = s.submissions_id
where guests.event_id = 1
ORDER BY submissions.created_at ASC;
SELECT submissions.created_at, guests.accepted
FROM submission
INNER JOIN guests
ON guests.(column to match against) = submissions.(column to match on)
where guests.event_id=1
ORDER BY submissions.created_at ASC;
As many others here have already said, your join is a little goofed. It's attempting to join the one row that matches in the guests table against every single row in the submission column.
You would need to do your join like this :
Inner join guest on guest.event_id = submissions_id
where guest.event_id = 1
When you join you need to join on two columns from different table (most of the time id columns)
You can read the MySQL example for more explanation. And here is the link to the MySQL reference manual

Mysql join query doesn't work for many to many relationship

I have 3 tables called
_partnership,
_partners,
_partnership_arm._partners = stores basic partner information
_partnership_arm = stores partnership arm details
_partnership = stores partners partnership records which includes the partner_id
arm_id which reference _partners.partner_id and _partnership_arm.arm_id.
So as an admin i want to select all details from the _partnership table which join other table reference without a where clause, but am having issue doing it.
here is my code
SELECT
_partnership.*,
_partners.names,
_partnership_arm.arm_name
FROM
`_partnership`
JOIN
`_partners`,`_partnership_arm` ON
_partnership.partner_id = _partners.partner_id
AND
_partnership.arm_id = _partnership_arm.arm_id
I also want a user to be able to select using a where clause
Please how can i achieve this?
Thank you.
SELECT
_partnership.*,
_partners.names,
_partnership_arm.arm_name
FROM
`_partnership`
JOIN
`_partners` ON _partnership.partner_id = _partners.partner_id
JOIN
`_partnership_arm` ON _partnership.arm_id = _partnership_arm.arm_id

Ok dumb question time. Linq to SQL. Join

I have two tables:
Clients, and a join table that has user id, a foreign key to clients, and some other stuff.
I want to do this SQL
select TblClient.* from TblClient
inner join tblUserClientProjJoin as b on TblClient.Client_ID = b.Client_FK
where b.User_fk = 2
So getting a list of 'clients' that a specific user has access to.
I want to apply this result to collection I can bind to controls.
Anyone?
var q = From c in db.TblClient join
ucp in db.tblUserClientProjJoin on
c.Client_ID equals ucp.Client_FK
select c;
I haven't tested this so you may need to modify it a little.
Hope this helps!