Filter a MySQL Result in Delphi - mysql

I'm having an issue with a certain requirement to one of my Homework Assignments. I am required to take a list of students and print out all of the students with credit hours of 12 or more. The Credit hours are stored in a separate table, and referenced through a third table
basically, a students table, a classes table with hours, and an enrolled table matching student id to Course id
I used a SUM aggregate grouped by First name from the tables and that all works great, but I don't quite understand how to filter out the people with less than 12 hours, since the SQL doesn't know how many hours each person is taking until it's done with the query.
my string looks like this
'SELECT Students.Fname, SUM(Classes.Crhrs) AS Credits
FROM Students, Classes, Enrolled
WHERE Students.ID = Enrolled.StudentID AND Classes.ID = Enrolled.CourseID
GROUP BY Students.Fname;'
It works fine and shows the grid in the Delphi Project, but I don't know where to go from here to filter the results, since each query run deletes the previous.

Since it's a homework exercise, I'm going to give a very short answer: look up the documentation for HAVING.

Beside getting the desired result directly from SQL as Martijn suggested, Delphi datasets have ways to filter data on the "client side" also. Check the Filter property and the OnFilter record.
Anyway, remember it is usually better to apply the best "filter" on the database side using the proper SQL, and then use client side "filters" only to allow for different views on an already obtained data set, without re-querying the same data, thus saving some database resources and bandwidth (as long as the data on the server didn't change meanwhile...)

Related

Is it possible to add an array value to a row in a MySql database

I am trying to do a CRUD operation with a form and I was wondering if like for example, a student is asked to register for say 4 subjects for an exam and they have to choose from a list, is it possible for those subject to appear in a single row on a column or do I have to create a seperate table for that?
It's generally good practice to add a separate table for that so that you can then use the information to, for example, find out which students need to take the economics exam. If you put comma separated values into a column, it's harder to get that information back.
If you're using newer versions of MySQL (5.7 or later), you could also check out the JSON column type which caters for storing more than just a single value in one column - but I'd still recommend using a separate table in most cases for good data design. Hope that helps!
It is possible. You could for instance write a string 'Math,Literature,Arts'.
However, you should only do this when you are never interested in the separate parts. If you never need a query to ask how many students registered for 'Math' or whether student 123 registered for 'Arts' etc., then no problem.
This would be a very rare case, though. Usually you are interested in the separate subjects, so store them separately, i.e. have a Student table, a subject table, and a student_subject table.

sql query to check many interests are matched

So I am building a swingers site. The users can search other users by their interests. This is only part of a number of parameters used to search a user. The thing is there are like 100 different interests. When searching another user they can select all the interests the user must share. While I can think of ways to do this, I know it is important the search be as efficient as possible.
The backend uses jdbc to connect to a mysql database. Java is the backend programming language.
I have debated using multiple columns for interests but generating the thing is the sql query need not check them all if those columns are not addressed in the json object send to the server telling it the search criteria. Also I worry i may have to make painful modifications to the table at a later point if i add new columns.
Another thing I thought about was having some kind of long byte array, or number (used like a byte array) stored in a single column. I could & this with another number corresponding to the interests the user is searching for but I read somewhere this is actually quite inefficient despite it making good sense to my mind :/
And all of this has to be part of one big sql query with multiple tables joined into it.
One of the issues with me using multiple columns would be the compiting power used to run statement.setBoolean on what could be 40 columns.
I thought about generating an xml string in the client then processing that in the sql query.
Any suggestions?
I think the correct term is a Bitmask. I could maybe have one table for the bitmask that maps the users id to the bitmask for querying users interests, and another with multiple entries for each interest per user id for looking up which user has which interests efficiently if I later require this?
Basically, it would be great to have a separate table with all the interests, 2 columns: id and interest.
Then, have a table that links the user to the interests: user_interests which would have the following columns: id,user_id,interest_id. Here some knowledge about many-to-many relations would help a lot.
Hope it helps!

How to eliminate database table row duplication

I have a question on databases and how information is displayed in regards to Primary and Foreign keys.
For example, there are three tables; Employees, Employee_tickets and Employee_comments.
Each employeecan have multiple tickets and also multiple comments. A foreign key is placed in the Employee tickets and Employee Comments table. My application is built in vb.net with Visual Studio and it is a desktop application. How can I query say.. Employee Name ('Jon Doe') and display all of his tickets in a grid as well as all of the comments people have made on him over time? I have created a View on the sql database which returns all of the information I require but for each ticket listed under ('Jon Doe') the View displays and Employee Name for every single ticket. Is there a way to display the employee name only once and then every ticket listed under that particular individual without displaying the Employee Name again or do I have to make Separate windows to segregate all of this?
This seems like a really dumb question and I cannot for the life of me figure out how to correctly display what is required in this situation.
Here is an example of what I am trying to explain:
So for troy there is one employee name entered in the Employee Names table, There is one CWB ticket entered in the CWB table but there are TWO PQ Cards entered in the PQR Ticket table. How Can I Display only one row for Troy and one Row for his CWB because there are only one of each entered in the tables then the two rows for the PQR Cards under his name?
I have created a view which gathers this information all into the one single view itself then bound the datagridview's to this View.
Your problem has nothing to do with databases. Rather, the issue is that you have an entity (the employee) that has two separate collections associated with it (tickets and comments) and you want to show the contents of both collections.
Doing this in a datagrid is difficult because in its simplest incarnation it's intended to show one collection of like items.
I can think of a number of possibilities:
In your code, convert each collection to a single string value and display that single string value on the row with the employee's name. This conversion could be to comma-separate a stringified version of each item in the collection (as suggested by BS123 in the comments) or could simply be a summary (eg "5 Tickets").
Put the basic employee information in one data grid and then have two additional data grids below it, one bound to the Tickets collection and one to the Comments collection.
Embed data grids directly in the main data grid, one in the Tickets column and one in the Comments column, and bind each one to the appropriate collection in the employee.
Your database structure is correct so don't change that, you simply need to solve the issue of presentation.
What you're missing here is a controller between your view and your model. Your view is presenting exactly what it was given to present - it's up to you to format it.
There are several possible solutions to this, and the correct one partially depends on needs and infrastructure.
If you infrastructure is solid and your needs are near real time, consider dropping separately querying to fill your second and third tables based on what is picked in the first. This will increase the load on the database, but your data will almost always be correct, and the data will come from the database the way you want to see it.
If the database-centered solution is not good for you, LINQ provides some good ways to filter your data into typed collections that would present exactly what you want the user to see.
To get the users:
Dim users = From l In data.lines
Group By FirstName = l.firstName, LastName = l.lastName
Into Tickets = Group, Count()
You can then present this object to your grid. While dynamic typing works here, I think it would be easier to manage view interactions with defined classes. I'll leave that part up to you. Do some searching on LINQ to fill in the rest of the blanks. It's pretty neat stuff.

Access query is duplicating unique records / Linked table issues

I hope someone can help me with this:
I have a simple query combining a list of names and basic details with another table containing more specific information. Some names will necessarily appear more than once and arbitrary distinctions like "John Smith 1" and "John Smith 2" are not an option, so I have been using an autonumber to keep the records distinct.
The problem is that my query is creating two records for each name that appears more than once. For example, there are two clients named 'Sophoan', each with a different id number, and the query has picked up each one twice resulting in four records (in total there are 122 records when there should only be 102). 'Unique values' is set to 'yes'.
I've researched as much as I can and am completely stuck. I've tried to tinker with sql but it always comes back with errors, I presume because there are too many fields in the query.
What am I missing? Or is a query the wrong approach and I need to find another way to combine my tables?
Project in detail: I'm building a database for a charity which has two main activities: social work and training. The database is to record their client information and the results of their interactions with clients (issues they asked for help with, results of training workshops etc.). Some clients will cross over between activities which the organisation wants to track, hence all registered clients go into one list and individual tables spin of that to collect data for each specific activity the client takes part in. This query is supposed to be my solution for combining these tables for data entry by the user.
At present I have the following tables:
AllList (master list of client names and basic contact info; 'Social Work Register' and 'Participant Register' join to this table by
'Name')
Social Work Register (list of social work clients with full details
of each case)
Social Work Follow-up Table (used when staff call social work clients
to see how their issue is progressing; the register has too many
columns to hold this as well; joined to Register by 'Client Name')
Participants Register (list of clients for training and details of
which workshops they were attended and why they were absent if they
missed a session)
Individual workshop tables x14 (each workshop includes a test and
these tables records the clients answers and their score for each
individual test; there will be more than 20 of these when the
database is finished; all joined to the 'Participants Register' by
'Participant Name')
Queries:
Participant Overview Query (links the attendance data from the 'Register' with the grading data from each Workshop to present a read-only
overview; this one seems to work perfectly)
Social Work Query (non-functional; intended to link the 'Client
Register' to the 'AllList' for data entry so that when a new client
is registered it creates a new record in both tables, with the
records matched together)
Participant Query (not yet attempted; as above, intended to link the
'Participant Register' to the 'AllList' for data entry)
BUT I realised that queries can't be used for data entry, so this approach seems to be a dead end. I have had some success with using subforms for data entry but I'm not sure if it's the best way.
So, what I'm basically hoping to achieve is a way to input the same data to two tables simultaneously (for new records) and have the resulting records matched together (for new entries to existing records). But it needs to be possible for the same name to appear more than once as a unique record (e.g. three individuals named John Smith).
[N.B. There are more tables that store secondary information but aren't relevant to the issue as they are not and will not be linked to any other tables.]
I realised that queries can't be used for data entry
Actually, non-complex queries are usually editable as long as the table whose data you want to edit remains 'at the core' of the query. Access applies a number of factors to determine if a query is editable or not.
Most of the time, it's fairly easy to figure out why a query has become non-editable.
Ask yourself the question: if I edit that data, how will Access ensure that exactly that data will be updated, without ambiguity?
If your tables have defined primary keys and these are part of your query, and if there are no grouping, calculated fields (fields that use some function to change or test the value of that field), or complex joins, then the query should remain editable.
You can read more about that here:
How to troubleshoot errors that may occur when you update data in Access queries and in Access forms
Dealing with Non-Updateable Microsoft Access Queries and the Use of Temporary Tables.
So, what I'm basically hoping to achieve is a way to input the same data to two tables simultaneously (for new records) and have the resulting records matched together (for new entries to existing records). But it needs to be possible for the same name to appear more than once as a unique record (e.g. three individuals named John Smith).
This remark actually proves that you have design issues in your database.
A basic tenet of Database Design is to remove redundancy as much as possible. One of the reasons is actually to avoid having to update the same data in multiple places.
Another remark: you are using the Client's name as a Natural Key. Frankly, it is not a very good idea. Generally, you want to make sure that what constitutes a Primary key for a table is reliably unique over time.
Using people's names is generally the wrong choice because:
people change name, for instance in many cultures, women change their family name after they get married.
There could also have been a typo when entering the name and now it can be hard to correct it if that data is used as a Foreign Key all in different tables.
as your database grows, you are likely to end up with some people having the same name, creating conflicts, or forcing the user to make changes to that name so it doesn't create a duplicate.
The best way to enforce uniqueness of records in a table is to use the default AutoNumber ID field proposed by Access when you create a new table. This is called a Surrogate key.
It's not mean to be edited, changed or even displayed to the user. It's sole purpose is to allow the primary key of a table to be unique and non-changing over time, so it can reliably be used as a way to reference a record from one table to another (if a table needs to refer to a particular record, it will contain a field that will hold that ID. That field is called a Foreign Key).
The names you have for your tables are not precise enough: think of each table as an Entity holding related data.
The fact that you have a table called AllList means that its purpose isn't that well-thought of; it sounds like a catch-all rather than a carefully crafted entity.
Instead, if this is your list of clients, then simply call it Client. Each record of that table holds the information for a single client (whether to use plural or singular is up to you, just stick to your choice though, being consistent is hugely important).
Instead of using the client's name as a key, create an ID field, an Autonumber, and set it as Primary Key.
Let's also rename the "Social Work Register", which holds the Client's cases, simply as ClientCase. That relationship seems clear from your description of the table but it's not clear in the table name itself (by the way, I know Access allows spaces in table and field names, but it's a really bad idea to use them if you care at least a little bit about the future of your work).
In that, create a ClientID Number field (a Foreign Key) that will hold the related Client's ID in the ClientCase table.
You don't talk about the relationship between a Client and its Cases. This is another area where you must be clear: how many cases can a single Client have?
At most 1 Case ? (0 or 1 Case)
exactly 1 Case?
at least one Case? (1 or more Cases)
any number of Cases? (0 or more Cases)
Knowing this is important for selecting the right type of JOIN in your queries. It's a crucial part of the design assumptions when building your database.
For instance, in the most general case, assuming that a Client can have 0 or more cases, you could have a report that displays the Client's Name and the number of cases related to them like this:
SELECT Client.Name,
Count(ClientCase.ID) AS CountOfCases
FROM Client
LEFT JOIN ClientCase
ON Client.ID = ClienCase.ClientID
GROUP BY Client.Name
You've described your basic design a bit more, but that's not enough. Show us the actual table structures and the SQL of the queries you tried. From the description you give, it's hard to really understand the actual details of the design and to tell you why it fails and how to make it work.

Showing data and counting from multiple databases in MySQL

I have two tables, that is joined in some way. I've spent the last hour googling around, not finding any concrete answers that worked in my case.
The case is, table 1 is called Clients, and table 2 is called Projects. I need to list all the client names, followed by number of projects related to that project and the project title.
For example:
Client 1 (2 projects)
- Project 1 title
- Project 2 title
Client 2 (0 projects)
Client 3 (1 project)
- Project 1 title
How is this doable, in the simplest and easiest way?
There are basically three parts to your query.
Joining the tables
Grouping the output by project
Counting the projects per client
The first is easy. It involves finding the client ID field in each table and use an JOIN clause specifying the two columns (one in each table) to correlate on. This will give you one row per project that also contains information for the matching client. This is almost what you're asking for.
It is tricky to put the second and third together in the one query and not one I would recommend. If you are going to be putting this in a program, then you can easily post-process the result from the query. To do this, you need to add an ORDER BY clause to specify sorting by client. That will put all the projects for each client in subsequent rows.
Now you can write a loop to process the output. As it does to, it has to watch for two things:
when the client ID changes
counting the projects
By doing this, it can easily display a "group header" for each client, and a "group footer" for the number of projects.
You don't say anything about your app, but I'd recommend separating querying from displaying. Let SQL get the data for you and then let something else do presentation.