I want to select result from different database based on a subsring value from columns.
Here is my table student:
Original_student Other_student
1010173 1240240
1010173 1240249
The 3rd digit in the number will be used to distinguish database. for example. I want the query be
select original_student, Other_student, month
from student join database-(substring(other_student,3,1).payment
My question is: How can I concatenate the substring to a database name or column name dynamically?
Thanks
Supposing you have a field to identify each student by a unique id (id_student), here is a cheap alternative:
CREATE OR REPLACE VIEW v_student_payment AS
SELECT 0 AS db, payment, id_student FROM database-0
UNION
SELECT 1 AS db, payment, id_student FROM database-1
UNION
SELECT 2 AS db, payment, id_student FROM database-2
UNION
SELECT 3 AS db, payment, id_student FROM database-3
/* here you have to add all databases you're using. There's a little maintenance cost, for if one day there's a new database to be created this view would have to be modified */
;
SELECT
original_student,
Other_student,
month,
v.payment
FROM
student s
JOIN v_student_payment v ON v.id_student = s.id_student AND v.db = SUBSTRING(other_student,3,1)
Did you try using a Case statement for checking with the join. Try looking at this link
Use Case Statement in Join
Related
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.
We want to select customers based on following parameters i.e. customer should be in:
specific city i.e. cityId=1,2,3...
specific customerId should be excluded i.e. customerId=33,2323,34534...
specific age i.e. 5 years, 7 years, 72 years...
This inclusion & exclusion list can be any long.
How should we design database for this:
Create separate table 'customerInclusionCities' for these inclusion cities and do like:
select * from customers where cityId in (select cityId from customerInclusionCities)
Some we do for age, create table 'customerEligibleAge' with all entries of eligible age entries:
i.e. select * from customers where age in (select age from customerEligibleAge)
and Create separate table 'customerIdToBeExcluded' for excluding customers:
i.e. select * from customers where customerId not in (select customerId from customerIdToBeExcluded)
OR
Create One table with Category and Ids.
i.e. Category1 for cities, Category2 for CustomerIds to be excluded.
Which approach is better, creating one table for these parameters OR creating separate tables for each list i.e. age, customerId, city?
IN ( SELECT ... ) can be very slow. Do your query as a single SELECT without subqueries. I assume all 3 columns are in the same table? (If not, that adds complexity.) The WHERE clause will probably have 3 IN ( constants ) clauses:
SELECT ...
FROM tbl
WHERE cityId IN (1,2,3...)
AND customerId NOT IN (33,2323,34534...)
AND age IN (5, 7, 72)
Have (at least):
INDEX(cityId),
INDEX(age)
(Negated things are unlikely to be able to use an index.)
The query will use one of the indexes; having both will give the Optimizer a choice of which it thinks is better.
Or...
SELECT c.*
FROM customers AS c
JOIN cityEligible AS b ON b.city = c.city
JOIN customerEligibleAge AS ce ON c.age = ce.age
LEFT JOIN customerIdToBeExcluded AS ex ON c.customerId = ex.customerId
WHERE ex.customerId IS NULL
Suggested indexes (probably as PRIMARY KEY):
customers: (city)
customerEligibleAge: (age)
customerIdToBeExcluded: (customerId)
In order to discuss further, please provide SHOW CREATE TABLE for each table and EXPLAIN SELECT ... for any of the queries actually work.
If you use the database only that operation, I recommend to use the first solution. Also the first solution is very simple to deploy.
The second solution fills up with junk the DB.
I am trying to retrieve the the first row among the duplicate row, THE FIRST OCCURED ***
--Table--
Order_No Product User
1 Book Student
2 Book Student
3 Book Student
I want to get the Order_No of the first duplicate row in JAVA, I have used DISTINCT and DISTINCT TOP 1 etc but nothing worked, NEED HELP
SELECT min(order_no), product, user
FROM 'table'
GROUP BY user, product
This is basic SQL?
SELECT min(order_no), product, user FROM table GROUP BY product, user
See also more information on GROUP BY
All fields not part of your group by must have some sort of way to determine which to pick of the n potentially different values. min() will pick the lowest value (even with strings and dates) while max() will pick the highest. You can also use First() and Last() to grab the value according to when they show up.
Supposing you had other values to pick from, you might see something like:
SELECT min(order_no), product, user, min(creation_date),
sum(quantity), first(billing_address)
FROM orders GROUP BY product, user
SELECT t.*
FROM table t
WHERE NOT EXISTS ( SELECT a
FROM table t2
WHERE t2.Product = t.Product
AND t2.User = t.User
AND t2.Order_No < t.Order_No
)
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
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.