Selecting specific records to run query on - mysql

I am trying to select a small number of records in a somewhat large database and run some queries on them.
I am incredibly new to programming so I am pretty well lost.
What I need to do is select all records where the Registraton# column equals a certain number, and then run the query on just those results.
I can put up what the db looks like and a more detailed explanation if needed, although I think it may be something simple that I am just missing.

Filtering records in a database is done with the WHERE clause.
Example, if you wanted to get all records from a Persons table, where the FirstName = 'David"
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
Your question indicates you've figured this much out, but are just missinbg the next piece.
If you need to query within the results of the above result set to only include people with more than two children, you'd just add to your WHERE clause using the AND keyword.
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
AND
NumberOfChildren > 3
Now, there ARE some situations where you really need to use a subquery. For example:
Assuming that each person has a PersonId and each person has a FatherId that corresponds to another person's PersonId...
PersonId FirstName LastName FatherId...
1 David Stratton 0
2 Matthew Stratton 1
Select FirstName,
LastName
FROM
Person
WHERE
FatherId IN (Select PersonId
From Person
WHERE FirstName = 'David')
Would return all of the children with a Father named David. (Using the sample data, Matthew would be returned.)
http://www.w3schools.com/sql/sql_where.asp

Would this be any use to you?
SELECT * from table_name WHERE Regestration# = number

I do not know what you have done up to now, but I imagine that you have a SQL query somewhere like
SELECT col1, col2, col3
FROM table
Append a where clause
SELECT col1, col2, col3
FROM table
WHERE "Registraton#" = number
See SO question SQL standard to escape column names?.

Try this:
SELECT *
FROM tableName
WHERE RegistrationNo = 'valueHere'

I am not certain about my solution. I would propose You to use view. You create view based on needed records. Then make needed queries and then you can delete the view.
View description: A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
Example:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
For more information: http://www.w3schools.com/sql/sql_view.asp

Related

What is the new table name after joining two tables in sql?

I read the previous posts but I couldn't find one that answered my question.
What would be the name of the table that is made by joining two tables? The reason why I need the name is because I would like to change the column name of the new table using the ALTER TABLE (Table name) RENAME COLUMN (A) to (B). If there is no specified name, how can I name the new table?
ex
SELECT
client_id
,last_name
FROM INDIVIDUAL_CLIENT
UNION ALL
SELECT
client_id
,bus_name
FROM BUSINESS_CLIENT;
I would like to rename the column to last_name/bus_name instead of last_name
In the case of a query what temporal table a query might create internally is not relevant, because you a making a query and getting data back, it doesn't stay in the database as a table, there is no such table. Unless we make it.
if You want TSQL to change a column name it would affect your union query and I base my answer on Your
'I would like to rename the column to last_name/bus_name instead of last_name'
And think this is what you're looking for. Please correct me if it isn't.
In generic SQL what we're doing is putting a label on both projections that are to be displayed in the same column
SELECT
client_id
,last_name [last_name/ bus_name]
FROM INDIVIDUAL_CLIENT
UNION ALL
SELECT
client_id
,bus_name [last_name/ bus_name]
FROM BUSINESS_CLIENT;
update, in MySQL notation uses AS and quotes instead of angle brackets
SELECT
client_id
,last_name as "last_name/ bus_name"
FROM INDIVIDUAL_CLIENT
UNION ALL
SELECT
client_id
,bus_name as "last_name/ bus_name"
FROM BUSINESS_CLIENT;

MySQL query returned 0 rows

I have a task to make a database only in MySQL. I made 11 tables and connected them via foreign keys. I tried to make a simple query in order to return name and lastname of the patient in his diagnose, but I always get only a header with the first and last name and analysis.
The patient's table has nameID, name, last name, ID serial number, date of birth and so on, but I wanted only name and last name for the test query.
The second table I joined is analysis, which has analysisID, patientID, doctorID, hospitalID, diagnosis and so on.
My query is like this:
SELECT pat.name, pat.lastname
FROM patient pat
JOIN analysis a ON pat.patientID = a.patientID
group by a.analysisID
order by pat.lastname
This query returns 0 rows. Please help, I am new at mySQL. I read a lot of tutorials, read posts here about this problem and I still didn't find a solution.
I assume that you want to eliminate any duplicate analysisID's for the same person with the use of group by. If so, you could use the following:
Select a.analysisID, pat.name, pat.lastname
from patient pat, analysis a
where pat.patientID = a.patientID
group by a.analysisID, pat.name, pat.lastname
What the above query will do is return only one record when the analysisID, name and lastname are all the same.

Selecting with multiple conditions in a Single SQL query

Table name is Student
I need the SQL query which gives names of students who are Math majors with more than 30 credits.
Thanks!
select *
from Student
where major='Math' and credits>30;
In MySQL
select firstName, lastName from Student where major='Math' and
credit>30;
Use Multiple conditions in WHERE Clause :
SELECT firstName, lastName
FROM Student
WHERE major='Math' AND credit>30;
select *
from student
where major ='Math' and credit> 30
Like others have rightly answered, the query should look like this and nothing more:
SELECT firstName, lastName FROM Student WHERE major='Math' AND credits>30;
It is worth nothing that, since you are mainly interested in just the full names of the students in the result, being specific on the name column is what is needed in the query and not SELECT ALL. This will greatly improve response time if you are working with a huge database.

Search MySql db with multiple "WHERE IN" and "OR" not working

Suppose I have a table like this:
Suppose my user inputs that he wants to see all records where gender is male AND eyecolor = grey.
I already have the following SQL for that:
SELECT User, question, answer FROM [Table] WHERE User IN (
SELECT User FROM [table] WHERE (question, answer) IN (
('gender', 'male'),
('eyecolor', 'grey')
)
)
GROUP BY User
HAVING count(distinct question, answer) = 2)
However, what if my user wants to see all records for (gender = male OR gender = female) AND eyecolor = grey ? How would I format the above sql query to get it to be able to find that?
(Keep in mind, this is a searchform, so eyecolor and gender are only a few fields used for searching; I need to be able to search with and/or combo's)
I'm thinking the only way I can get this to work is something like:
SELECT User
FROM [table]
WHERE (gender = male OR gender = female) AND eyecolor = blue
And my php would have to build the query so that if the user enters more fields, the query expands with more WHERE's etc.?
I have been searching all over but have not been able to get it to work.. Admittedly I'm not the world's greatest with this.
http://sqlfiddle.com/#!2/2e112/1/0
select *
from stuff
where ID in (
select ID
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey')
group by ID
having count(ID)=2
)
where 2 is the number of conditions in the nested where statement. If you run that nested select on its own, it will give you just a distinct list of ID's that fit the conditions. The outer statement allows the query to return all records for the ID's that fit those conditions.
i edited this because.... i was wrong before
k... http://sqlfiddle.com/#!2/2f526/1/0
select *
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
for this query, we return one row that matches any of those conditions for any ID. only ID's that satisfy at least one of those conditions will appear in the results.
select ID, count(*) as matches
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
group by ID;
then we add the group by, so we can see how many rows are returned for each user and how many conditions they met (count(*)).
select ID
from stuff
where (question='gender' and answer in ('male','female')) or
(question='eyecolor' and answer='grey') or
(question='city' and answer in ('madrid','amsterdam'))
group by ID
having count(ID)=3;
the having count(ID)=3; is what makes this query work. we only want ID's that had 3 rows returned because we have 3 conditions.
and.... we can't use and because no row in that table will ever meet more than one of those conditions at a single time. question cannot be gender, eyecolor and city all at the same time. it has to do with your table layout. city will never be both madrid and amsterdam at the same time.... and will give us nothing. so... by using the having and an or... we can do stuff that's happy...?
and to go on a tangent.... if your table looked like this:
ID gender eyecolor city
---------------------------------------------
100 male blue madrid
200 female grey amsterdam
300 male brown somewhere
you would use and because....
select *
from table
where gender in ('male','female') and
city in ('madrid','amsterdam') and
eyecolor = 'grey'
but your table is a special one and didn't want to go that way because you really shouldn't have a column for every question... what if they change or what if you add 20? that'd be hard to maintain.
and....
select ID
from stuff
where question in ('gender','eyecolor','city') and
answer in ('male','female','grey','madrid','amsterdam')
group by ID
having count(ID)=3;
does also work but i would really be cautious with that because.. the questions and answers should stay together and be explicit because.... what if it was a dating service? and male could be an answer for a person's own gender or the gender they want to date and by doing question='gender' and answer in ('male','female') you are specifying exactly what you mean and not assuming that certain information is only a valid answer for one question.

Combining count(*) with SQL statements into one table

I have two tables in my MySQL database (table1 and table 2). I want to write a SQL query that outputs some summary stats in a nicely formatted report.
Let's for an example consider a first SQL query that takes the users over 57 year of age from the first table
SELECT count(*) AS OlderThank57
FROM table1
WHERE age >57
And from the second table we want to get the number of users that are female
SELECT count(*) AS FemaleUsers
FROM table2
WHERE gender = "female"
Now I want to have an output like the following
Number of Felame users from table 2: 514
Number of users over the age of 57 from table 1: 918
What is the best way of generating such a report?
I would offer to expand one level from Adrian's answer... return as two separate fields so you could place them separately in a report, or align / format the number, etc
SELECT 'Number of Female users from table 2:' as Msg,
count(*) as Entries
FROM table1
WHERE age >57
UNION ALL
SELECT 'Number of users over the age of 57 from table 1:' as Msg,
count(*) as Entries
FROM table2
WHERE gender = "female"
You might have to force both "Msg" columns to the same padded length, otherwise one might get truncated. Again, just another option...
You could always try the WITH ROLLUP directive when using a GROUP BY:
SELECT COUNT(*), gender FROM table1 GROUP BY gender WITH ROLLUP
If you want to get a bit crazy you can always make a series of IFs that handles the logic for one or more thing at a time:
SELECT COUNT(*) IF(gender='female', 'female', IF(age>57, 'older_than_57', '*')) AS switch FROM table1 GROUP BY switch WITH ROLLUP
SELECT CONCAT('Number of users over the age of 57 from table 1:', count(*))
FROM table1
WHERE age >57
UNION ALL
SELECT CONCAT('Number of Felame users from table 2: ', count(*))
FROM table2
WHERE gender = "female"
I don't have mysql database to check it, so you might have to cast count(*) to string.
A union is your only option if you don't have a normalized database. Your other option is to better standardize/normalize your db so you can run much more efficient queries.