parameters for nested mysql views - mysql

Here is a table with barcodes which belongs to different warehouses.
Barcode | Warehouse
_____________________________
1111111 | A
2222222 | B
1111111 | C
3333333 | A
And here is a table with boxes containing barcodes.
Barcode | Box
_____________________________
1111111 | 0001
2222222 | 0002
Each warehouse's available stock is its amount in the first table, plus all the amount in boxes.
Example for warehouse A:
Barcode
_________
1111111 (from its warehouse)
3333333 (from its warehouse)
1111111 (from a box)
2222222 (from a box)
This is a simplified example. After retrieving the total amount of barcodes, I cross it with a lot of other queries and tables to transform it into a human-readable report.
Ok,
The idea would be a server-side query.
Every client (VBA msaccess) would retrieve the query and filter it using its warehouse code.
Warehouse A would call it like this:
select * from finalQuery where warehouse like 'A' <--- BUT it won't work, because boxes' barcodes haven't the warehouse field, thus, they would be excluded.
The "where" clause should be performed before the UNION ALL.
Would it be possible to use parameters in order to exclusively retrieve a warehouse's barcodes + all boxes' barcodes in a server-side query? Even though the user calls the last query with its code, it should push the parameter down to the first nested query.
Or any other trick? Maybe my scheme is wrong?
The problem manipulating queries in the client side, is that it becomes painstakingly SLOW, because as I said, after joining barcodes, I use the resulting query for building other queries.
Hope I explaied it clearly. It is somewhat complex to explain. I would appreciate any suggestion, trick, idea, etc
Thank you.

I think what you're looking for is a JOIN statement. You can join the Barcode-Warehouse table with the Barcode-Box table using the common Barcode column. This article is a great explanation: http://www.tutorialspoint.com/mysql/mysql-using-joins.htm.
Your server side query will end up being something like this:
SELECT Barcode, Box, Warehouse FROM Barcode-Warehouse LEFT JOIN Barcode-Box USING (Barcode);
This should result in a result set that has Barcode, Box, and Warehouse on each line. Your users would then be able to filter that result by Warehouse and retrieve only the records that they are interested in.

Found a way to solve it:
Can I create view with parameter in MySQL?
I filter the first query by adding:
"where warehouse=function()"
When I call the final query, I add the parameter for the function as explained in the post. Easy, simple.
thank you

Related

Using Lookup and getting a count from each Dataset

I have two datasets and I'm using Lookup to get one result, but the total is only from one dataset. I've tried and tried, but I'm having no luck.
First Dataset is called MedCond
This is the Data:
Drug_Name
Start_Date
Stop_Date
InmateID
Drug_Indication
Created
ID
Second Dataset is called ProblemList
This is the Data:
Medical_Condition
Inmate_ID
Created
ID
Drug Indication and Medical Condition are the same. I want to get a combined total of both.
This only gives me the count of the Drug Indications (which I have them grouped on) =Count(Lookup(Fields!Drug_Indication.Value,Fields!Medical_Condition.Value,Fields!Medical_Condition.Value, "ProblemList"))
I feel like I've tried everything under the sun. I'm extremely exasperated. I'm trying to get a total of each of the conditions/Indications that come from each dataset. For instance, One condition/Indication might be Addiction. There may be four addictions in from the Drug_Indication in the MedCon dataset and five addictions from the Medical_Condition in the ProblemList. I want to see Addictions 9 on the table and so and so forth for each Drug Indication/Medical Condition.
Thanks in advance for your help! Save my sanity. :) I'm sure it's probably something simple?
Tara
Thank you. I've tried using the Inmate_ID and InmateID as the key to join, but I still end up with only one of counts of either Medical_Condition or Drug_Indication.
As an example, there might be 10 addictions in one and 15 addictions in the other. I need them to be grouped under the title addiction (and whatever other titles there might be) with the total being 25.
It would look something like this.
Example Look
Something like this is close, but the counts aren't quite right.
=Count(Lookup(Fields!InmateID.Value, Fields!Inmate_ID.Value, Fields!Medical_Condition.Value, "ProblemList")) + Count(Fields!Drug_Indication.Value)
Maybe it's the way I'm grouping? How do you group on a combination of values such as Medical_condition and Drug_Indication?
Thanks again!
Tara
I think you used the Lookup() wrong. When I look at your two datasets (for me) the key to join the two datasets would be Inmate_ID.
=Lookup(Fields!InmateID.Value, Fields!Inmae_ID.Value, Fields!Medical_Condition.Value, "SecondDatasetName")
This would result in a table like this (The last column comes form the lookup above):
Drug_Name | Start_Date | Stop_Date | InmateID | Drug_Indication | Created | ID | Medical_Condition
Now you can just get the total per column:
Drug_Name | Start_Date | Stop_Date | InmateID | Drug_Indication | Created | ID | Medical_Condition
Total1 Total2
To sum Total1 and Total2 you can add a new tablix and reference to the textbox totals like this:
=ReportItems!Total1TextboxName.Value + ReportItems!Total2TextboxName.Value

How to Combine Fields from Two Datasets SSRS?

I am working on a report to show the total number of hours an employee spent working. Our company tracks labor hours by Service Request and Work Order so I need to bring totals for each into the report.
I created two datasets- one for Work Orders and one for Service Requests. Ideally, I would like to combine the total number of Work Order hours with the total number of Service Request hours and present that number listed by employeeID since both datasets have the employeeID field.
I thought it would be as simple as:
=(SUM(Fields!TOTALHOURS_WO.Value, "DataSet1") + SUM(Fields!TOTALHOURS_SR.Value, "DataSet2"))
I don't get an error, however, I am getting a number which repeats for each employee so I know I'm doing something wrong.
Any help is greatly appreciated.
Mal,
As #StevenWhite mentioned, LOOKUP is probably the function you are looking for.
Here is an example for you. For the example datasets:
EmployeeID | TOTALHOURS_WO
-----------------------------------
123 | 12
456 | 3
EmployeeNum| TOTALHOURS_SR
-----------------------------------
123 | 2
456 | 5
You will note that each table in a SSRS report needs a DataSet assigned to it. I will assume your table is using our first DataSet, which we will name "DataSet1". The second dataset above will be "DataSet2".
For your total hours you will use an expression. It should look something like this:
=TOTALHOURS_WO + LOOKUP(Fields!EmployeeID.Value, Fields!EmployeeNum.Value, Fields!TOTALHOURS_SR.Value, "DataSet2")
So you will be adding the TOTALHOURS_WO from your local dataset to the result from the LOOKUP function. What lookup is doing is taking the first field from your local dataset, finding a match in the dataset provided to the function (as a string), and returning the field from the row it matched to. The last parameter is the dataset to search.
Just in case you get an error... it's always a good idea to cast data to the type you want to work with in case it comes in wrong. So...
=CINT(TOTALHOURS_WO) + CINT(LOOKUP(Fields!EmployeeID.Value, Fields!EmployeeNum.Value, Fields!TOTALHOURS_SR.Value, "DataSet2"))
This assumes you have a one to one match on employee ID. If you have to SUM both fields you can try this:
=SUM(CINT(TOTALHOURS_WO)) + SUM(LOOKUPSET(Fields!EmployeeID.Value, Fields!EmployeeNum.Value, CINT(Fields!TOTALHOURS_SR.Value), "DataSet2"))
SUM for TOTALHOURS_WO will give you the SUM in your current table group (so make sure you are grouping by staff ID in the table). It will then add it to the SUM of LOOKUPSET. LOOKUPSET works the same as lookup but returns an array of matches instead of the first.
Hope this helps.

MySQL - Difficulty getting sum with other data between two tables

I am using the Invision Power Board suite for purchases, but they do not provide a way to get the total a customer has paid. So I am attempting to write an SQL Query for this information. My knowledge of SQL is extremely limited, so ... I may be taking the wrong approach.
From what I have gathered, the information I need is on two tables, but the way it outputs is not useful to me since it outputs every individual purchase, with only the member's unique ID (relatively useless in bulk operations and examination)
I have so far gotten to this point...
SELECT member_id, email, name,
SUM(ibf_nexus_invoices.i_total) as SUM_TOTAL
FROM ibf_members
RIGHT JOIN ibf_nexus_invoices ON ibf_members.member_id = ibf_nexus_invoices.i_member
WHERE ibf_nexus_invoices.I_status = "paid";
This takes everything from the members table and the invoices table, and outputs it like this..
------------------------------------------------------------
member_id | email | name | SUM_TOTAL |
------------------------------------------------------------
4 | email#domain.com | "Derek" | 184.22 |
------------------------------------------------------------
At first glance, this looks like what I want. But it only returns one person, not all of the people in the member's list. Is anyone versed enough with SQL to help steer me in the right direction?
You need to add
GROUP BY member_id
to the end of the query to get a row per person. Otherwise, aggregate functions like SUM() combine all the rows in the result.

mysql optimize data content: multi column or simple column hash data

I actually have a table with 30 columns. In one day this table can get around 3000 new records!
The columns datas look like :
IMG Name Phone etc..
http://www.site.com/images/image.jpg John Smith 123456789 etc..
http://www.site.com/images/image.jpg Smith John 987654321 etc..
I'm looking a way to optimize the size of the table but also the response time of the sql queries. I was thinking of doing something like :
Column1
http://www.site.com/images/image.jpg|John Smith|123456789|etc..
And then via php i would store each value into an array..
Would it be faster ?
Edit
So to take an example of the structure, let's say i have two tables :
package
package_content
Here is the structure of the table package :
id | user_id | package_name | date
Here is the structure of the table package_content :
id | package_id | content_name | content_description | content_price | content_color | etc.. > 30columns
The thing is for each package i can get up to 16rows of content. For example :
id | user_id | package_name | date
260 11 Package 260 2013-7-30 10:05:00
id | package_id | content_name | content_description | content_price | content_color | etc.. > 30columns
1 260 Content 1 Content 1 desc 58 white etc..
2 260 Content 2 Content 2 desc 75 black etc..
3 260 Content 3 Content 3 desc 32 blue etc..
etc...
Then with php i make like that
select * from package
while not EOF {
show package name, date etc..
select * from package_content where package_content.package_id = package.id and package.id = package_id
while not EOF{
show package_content name, desc, price, color etc...
}
}
Would it be faster? Definitely not. If you needed to search by Name or Phone or etc... you'd have to pull those values out of Column1 every time. You'd never be able to optimize those queries, ever.
If you want to make the table smaller it's best to look at splitting some columns off into another table. If you'd like to pursue that option, post the entire structure. But note that the number of columns doesn't affect speed that much. I mean it can, but it's way down on the list of things that will slow you down.
Finally, 3,000 rows per day is about 1 million rows per year. If the database is tolerably well designed, MySQL can handle this easily.
Addendum: partial table structures plus sample query and pseudocode added to question.
The pseudocode shows the package table being queried all at once, then matching package_content rows being queried one at a time. This is a very slow way to go about things; better to use a JOIN:
SELECT
package.id,
user_id,
package_name,
date,
package_content.*
FROM package
INNER JOIN package_content on package.id = package_content.id
WHERE whatever
ORDER BY whatever
That will speed things up right away.
If you're displaying on a web page, be sure to limit results with a WHERE clause - nobody will want to see 1,000 or 3,000 or 1,000,000 packages on a single web page :)
Finally, as I mentioned before, the number of columns isn't a huge worry for query optimization, but...
Having a really wide result row means more data has to go across the wire from MySQL to PHP, and
It isn't likely you'll be able to display 30+ columns of information on a web page without it looking terrible, especially if you're reading lots of rows.
With that in mind, you'll be better of picking specific package_content columns in your query instead of picking them all with a SELECT *.
Don't combine any columns, this is no use and might even be slower in the end.
You should use indexes on a column where you query at. I do have a website with about 30 columns where atm are around 600.000 results. If you use EXPLAIN before a query, you should see if it uses any indexes. If you got a JOIN with 2 values and a WHERE at the same table. You should make a combined index with the 3 columns, in order from JOIN -> WHERE. If you join on the same table, you should see this as a seperate index.
For example:
SELECT p.name, p.id, c.name, c2.name
FROM product p
JOIN category c ON p.cat_id=c.id
JOIN category c2 ON c.parent_id=c2.id AND name='Niels'
WHERE p.filterX='blaat'
You should have an combined index at category
parent_id,name
AND
id (probably the AI)
A index on product
cat_id
filterX
With this easy solution you can optimize queries from NOT DOABLE to 0.10 seconds, or even faster.
If you use MySQL 5.6 you should step over to INNODB because MySQL is better with optimizing JOINS and sub queries. Also MySQL will try to run them into MEMORY which will make it a lot faster aswel. Please keep in mind that backupping INNODB tables might need some extra attention.
You might also think about making MEMORY tables for super fast querieing (you do still need indexes).
You can also optimize by making integers size 4 (4 bytes, not 11 characters). And not always using VARCHAR 255.

MySQL Query Search using Multiple Rows

Firstly I'd like to start by apologizing for the potentially miss-leading title... I am finding it difficult to describe what I am trying to do here.
With the current project I'm working on, we have setup a 'dynamic' database structure with MySQL that looks something like this.
item_details ( Describes the item_data )
fieldID | fieldValue | fieldCaption
1 | addr1 | Address Line 1
2 | country | Country
item_data
itemID | fieldID | fieldValue
12345 | 1 | Some Random Address
12345 | 2 | United Kingdom
So as you can see, if for example I wanted to lookup the address for the item 12345 I would simply do the statement.
SELECT fieldValue FROM item_data WHERE fieldID=1 and itemID=12345;
But here is where I am stuck... the database is relatively large with around ~80k rows and I am trying to create a set of search functions within PHP.
I would like to be able to perform a query on the result set of a query as quickly as possible...
For example, Search an address name within a certain country... ie: Search for the fieldValue of the results with the same itemID's as the results from the query:
'SELECT itemID from item_data WHERE fieldID=2 and fieldValue='United Kingdom'..
Sorry If I am unclear, I have been struggling with this for the past couple of days...
Cheers
You can do this in a couple of ways. One is to use multiple joins to the item_data table with the fieldID limited to whatever it is you want to get.
SELECT *
FROM
Item i
INNER JOIN item_data country
ON i.itemID = country.itemID
and fieldid = 2
INNER JOIN item_data address
ON i.itemID = country.itemID
and fieldid = 1
WHERE
country.fieldValue= 'United Kingdom'
and address.fieldValue= 'Whatever'
As an aside this structure is often referred to as an Entry Attribute Value or EAV database
Sorry in advance if this sounds patronizing, but (as you suggested) I'm not quite clear what you are asking for.
If you are looking for one query to do the whole thing, you could simply nest them. For your example, pretend there is a table named CACHED with the results of your UK query, and write the query you want against that, but replace CACHED with your UK query.
If the idea is that you have ALREADY done this UK query and want to (re-)use its results, you could save the results to a table in the DB (which may not be practical if there are a large number of queries executed), or save the list of IDs as text and paste that into the subsequent query (...WHERE ID in (...) ... ), which might be OK if your 'cached' query gives you a manageable fraction of the original table.