Shortcut for aliasing many columns on multiple joins? - mysql

My first mySQL project.
I am migrating a FileMaker DB to mySQL and having trouble with how to efficiently handle duplicate field (column) names from 3 left joined tables, combined with the fact that each table is supplying a large number of columns (50+). I understand the concept of aliasing columns. Is there a better way than to create several hundred alias lines to handle each column from each table? I've searched the site and not found a discussion of handling a large number of columns, which is common in FileMaker DBs...perhaps not in mySQL.
Current code is below, where I created the aliases for only ONE (WebPublish) of the ~50 fields for each of the 3 joined tables:
$query = "SELECT
Artwork.WebPublish as Artwork_WebPublish,
Artist.WebPublish as Artist_WebPublish,
Location.WebPublish as Location_WebPublish
FROM Review
LEFT JOIN Artwork ON Review._kf_ArtworkID = Artwork.__kp_ArtworkID
LEFT JOIN Artist ON Review._kf_ArtistID = Artist.__kp_ArtistID
LEFT JOIN Location ON Review._kf_LocationID = Location.__kp_LocationID
WHERE __kp_ReviewID = ?";
This query produces the desired response for one column from each joined table:
Array
(
[Artwork_WebPublish] => Yes
[Artist_WebPublish] => No
[Location_WebPublish] => Maybe
)
The question is whether I need to expand the aliases the long way to include 49 times more data.
Thanks for you help.

No, there's no SQL syntax for giving column aliases in a "batch" mode, for example applying the table name as a prefix to all columns (by the way, SQLite does support that feature by default).
One way to solve this is to refer to columns by ordinal position instead of by name, in whatever language you use to fetch the results.
Another solution is to define your tables with distinct column names so you avoid the name conflict. Some SQL identifiers, for example constraint names, are already required to be unique within the database they reside in, not only unique within a table. It may be a naming convention you want to use to apply the same rule to column names.

Related

How do the fields in "SHOW COLUMNS" command map to specific tables?

Here is a View called viewwithcommonfield :
SELECT
`schematopologytest01`.`talpha`.`CommonField` AS `CommonField_tAlpha`,
`schematopologytest01`.`tbeta`.`CommonField` AS `CommonField_tBeta`
FROM
(`schematopologytest01`.`talpha`
JOIN `schematopologytest01`.`tbeta`)
When I execute
SHOW FULL fields FROM viewwithcommonfield IN SchemaTopologyTest01
I get this:
How do I map the fields back to specific tables? Can I write a view against the tables in information_schema?
Here are the table structures that are referenced in the view. The tables share a common field called CommonField:
No, there is no metadata available to map views of a column back to the original column in a base table. That would require multiple tables, because any given expression in the select-list may reference multiple columns from different tables.
Consider:
SELECT CONCAT(
`schematopologytest01`.`talpha`.`AlphaFieldA`,
`schematopologytest01`.`tbeta`.`BetaFieldE`) AS `ConcatenatedField`
FROM `schematopologytest01`.`talpha`
JOIN `schematopologytest01`.`tbeta` ON ...
Which table and column would ConcatenatedField list as its origin? It would have to be stored in two rows of another INFORMATION_SCHEMA table.
There are also select-list expressions possible in a view that don't reference any base table:
CREATE VIEW ViewNow AS SELECT NOW() AS `now`;
What about columns that are themselves scalar subqueries? Or references to stored functions? Or an aggregate function like COUNT() or SUM() where the value is not found in any base table?
Many views do not derive their data from base tables deterministically at all. Edit: What I mean is that it's not always possible to know which rows or columns are the source of data in a view, because they results are combined in some ways. It's probably more clear to say that reversing the query to get the original data is not always possible, depending on the query.
It's not possible to update those views. But if there were metadata about where the data "came from," there would have to be something in the metadata to indicate that. It would be impractical because it would be complex, and have little value.

MySQL Command what does a point mean?

I'm a newbie in mysql and have to write a implemention for a custom mysql asp.net identity storage.
I follow this tutorial and the first steps are done.
https://learn.microsoft.com/en-us/aspnet/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider
Now i have the follow mysql command:
"Select Roles.Name from UserRoles, Roles where UserRoles.UserId = #userId and UserRoles.RoleId = Roles.Id"
My problem is now that i dont know how the table have to look for this request?
I would say:
Tablename : Roles
Select: Roles and Name? or is it a name?
same with UserRoles.UserID and UserRoles.RoleId
What does the point mean?
Thanks a lot
You question is quite unclear, however, if I understood correctly, you can't figure out clearly how the database schema you are using is structured and what you'll get from this query.
The query you have written SELECTs the data field called Name from the table called Roles. In order to do this, the query uses data coming from two tables: one is the Roles table itself, the other is called UserRoles.
It will extract Names data from the Roles table only for the Roles entries that have the Id field matching with the RoleId field of the entries in the UserRoles table that have the UserId equal to the given #UserId.
In other words, this SELECT query in will give you as a result a list of Names coming from the entries in the Roles table which match the given conditional check, which is what is written after the where SQL condition: where UserRoles.UserId = #userId and UserRoles.RoleId = Roles.Id.
Finally, the point "." in SQL queries is used to disambiguate between fields (or columns, if you want to call it so) with same name but coming from different tables. It is quite common that all the tables have an Id field, for example. You can identify the correct Id field in your database by writing Table1.Id, Table2.Id, and so on. Even if you don't have naming conflicts in your tables columns, adding the table name can be very good for code readability.
Edit:
As other users correctly pointed out in the comments to your question, you should also have a look to what an SQL JOIN operation is. Since you are searching data using information coming from different tables, you are actually doing an implicit JOIN on those tables.

Recommended method to SELECT multiple columns within a nested subquery in mySQL

What methods are recommended for Selecting multiple columns within a nested subquery? It's been a while since I've coded any queries and I'm having some difficulty wrapping my head around this. The specific challenge is on Line 2 of the code below. The IN operand doesn't quite work here (see error message below), and I'm not sure if it's simply a matter of the syntax I'm using, and/or there is a much better way to go about this (i.e. using the HAVING operand or a JOIN statement)
SELECT * FROM Rules WHERE Rules.LNRule_id
IN(SELECT LNRule_id1,LNRule_id2,LNRule_id3,LNRule_id4 FROM Silhouette
WHERE Silhouette.Silhouette_Skirt=(SELECT Silhouette_Skirt FROM Style
WHERE Style.Style_Skirt='$Style_Skirt')
)
The purpose of this query is to SELECT all the relevant rows in table Rules for a particular value in table Style (i.e. $Style_Skirt), which it does by matching it to one of several factors - in this case the garment's Silhouette. What I am therefore trying to do in this portion of the query is SELECT all rows in table Rules who's ID (LNRule_id) matches values in any of the specified columns in table Silhouette
(SELECT LNRule_id1,LNRule_id2,LNRule_id3,LNRule_id4 FROM Silhouette WHERE Silhouette.Silhouette_Skirt=(...))
Edit
There is a many-to-many relationship (each Silhouette has several applicable Rules, and each Rule can apply to several Silhouettes). All the rules reside in the table 'Rules' (one per row), and each rule has an id ('LNRule_id'). The table 'Silhouette' has columns which tell it which rows need to be called from 'Rules' by 'LNRule_id' (LNRule_id1,2,3,4 indicate which Rules should be called, and store the values of the id's for the relevant rows in table 'Rules')
The error message currently being generated by the IN Operand is:
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1
column(s)
I think you want this query
SELECT * FROM Rules r
JOIN Silhouette s
(ON r.LNRule_id=s.LNRule_id1
OR r.LNRule_id=s.LNRule_id2
OR r.LNRule_id=s.LNRule_id3
OR r.LNRule_id=s.LNRule_id4)
JOIN Style st
ON s.Silhouette_Skirt=st.Silhouette_Skirt
WHERE st.Silhouette_Skirt = '$Style_Skirt'
mysql is complaining that on one side of IN you have a single column, and on the other side you have a multi-column rowset. In order for the IN operator to work, the rowset on the right side of IN must have the exact same number of columns as the left side; in this case, one column.
What you are trying to accomplish could perhaps be achieved if you did something like WHERE LNRule_id IN( SELECT LNRule_Id1 ...) OR LNRule_id IN( SELECT LNRule_Id2 ...) OR ... OR ... but the resulting query would be a monstrosity, and its performance would be horrendous. There may be other ways to go about it too, but anything you try will probably be similarly atrocious.
I do not have enough information to be absolutely sure about what I am saying, but it seems to me that the reason why you have this problem is that your database schema is not normalized. Generally, whenever you see a table with a group of columns having names that all begin with the same prefix and end with a number, it means that someone, somewhere, did not normalize their data.
To address the edit in your question, what you have implemented might conceptually be a many to many relationship, but as far as relational databases are concerned, (you know, the science, the theory, the established practices, the approaches necessary to get things to actually work,) it is definitely not a many to many relationship. Many to many relationships are most certainly not implemented with column1, column2, column3, ... columnN. To be sure that I am not making this stuff up, you can read what others say about many to many relationships here:
Many-to-many relations in RDBMS databases
So, my suggestion, if I correctly understand what is going on, would be to introduce a new table, called SilhouetteRules, which contains two columns, silhouette_id and rule_id. This table will implement a many-to-many relationship between silhouettes and your rules. Then of course you get rid of all the rule1, rule2, rule3, etc. columns from Silhouette.
Once you have done that, you can obtain all silhouettes and all rules associated with them using a query like this:
SELECT * FROM Silhouette
LEFT JOIN SilhouetteRules ON
Silhouette.id = SilhouetteRules.silhouette_id
LEFT JOIN Rules ON
SilhouetteRules.rule_id = Rules.id
The above query will yield multiple rows for each silhouette, where the silhouette fields will be identical from row to row, and only the rule fields will differ. Do not be surprised by this, that's how relational databases work.
Given a given_silhouette_id, you can retrieve all rules associated with it using a query like this:
SELECT * FROM Rules
LEFT JOIN SilhouetteRules ON
Rules.id = SilhouetteRules.rule_id
WHERE
SilhouetteRules.silhouette_id = given_silhouette_id
So, you are going to be using this query as a subquery in queries like the one in the question.
Now, regarding the query in the question, I am unable to tell you exactly how you would need to modify it to get it to work with the normalization that I proposed, because I cannot make sense of it. You see, even if you fix the problem that you currently have with SELECT * FROM table WHERE single-column IN multi-column-rowset, there is another problem further down: the WHERE Silhouette.Silhouette_Skirt=(SELECT ... part would not work either, because you cannot compare the value of a column against the result of a select statement. So, I do not know what you are trying to do there. Hopefully, once you normalize your schema and fix the first problem with your query, then the solution to the second problem will become obvious, or you can ask another question on stackoverflow.
P.S. did Mihai's answer work?

Creating View: Multiple Foreign Key Relations to Single Table

I have a table, tblNoComp, that has two columns, both foreign keys pointing to tblPackage.ID. The purpose of tblNoComp is to store which packages are not compatible with each other, by simply storing the ID of those packages in two columns, OneID and TwoID.
May not be the best way of storing it, but since multiple packages aren't compatible with others, it seemed to be the most logical.
Attempting to create a view that shows the tblPackage.Name for the two side by side - I have the following, but unsure how to get the TwoID Package Name..
SELECT tblNoComp.OneID, tblPackages.Package,tblNoComp.TwoID,tblPackages.Package
FROM tblNoComp, tblPackages
WHERE (tblNoComp.OneID = tblPackages.PID)
Currently the second tblPackages.Package is simply showing OneID name, not TwoID.. Not sure how to resolve?
Thank you!
--Apologies if a simple question, I've searched for an hour but haven't quite been able to describe my problem correctly.
The code you have in your comment:
SELECT
tblNoComp.OneID,
tblPackages.Package AS OneIDPackageName,
tblNoComp.TwoID,
tblPackages.Package AS TwoIDPackageName
FROM
tblNoComp
LEFT JOIN tblPackages
ON tblNoComp.OneID = tblPackages.PID
Is aliasing the columns instead of the tables. The idea behind the aliasing is to JOIN the same table twice as two different tables, using two different aliases. You're only joining it once and trying to use it twice.
You probably intent something more like this:
SELECT
tblNoComp.OneID,
tblOnePackages.Package AS OneIDPackageName,
tblNoComp.TwoID,
tblTwoPackages.Package AS TwoIDPackageName
FROM
tblNoComp
LEFT JOIN tblPackages AS tblOnePackages
ON tblNoComp.OneID = tblOnePackages.PID
LEFT JOIN tblPackages AS tblTwoPackages
ON tblNoComp.TwoID = tblTwoPackages.PID
(Note that I don't have a MySQL syntax checker handy, so this may need to be tweaked in order to run properly.)
Note that the same table is joined twice on two different keys, and that each time it's given a different alias so that it can be referenced within the SELECT clause as two separate tables.

Joining a table stored within a column of the results

I want to try and keep this as one query and not use PHP, but it's proving to be tough.
I have a table called applications, that stores all the applications and some basic information about them.
Then, I have a table with all the types of applications in it, and that table contains a reference to another table which stores more specific data about the specific type of application in question.
select applications.id as appid, applications.category, type.title as type, type.id as tid, type.valuefld, type.tablename
from applications
left join type on applications.typeid=type.id
left join department on type.deptid=department.id
where not isnull(work_cat)
and work_cat != ''
and applications.deleted=0
and datei between '10-04-14' and '11-04-14'
order by type, work_cat
Now, in the old version, there is another query on every single result. Over hundreds of results... that sucks.
This is the query I'd like to integrate so I can get all the data in one result row. (Old is ASP, I'm re-writing it in PHP)
query = "select sum("&adors.fields("valuefld")&") as cost, description from "&adors.fields("tablename")&" where appid = '"&adors.fields("tablename")&"'"
Prepared statements, I'm aware, are the best solution, but for now they are not an option.
You can't do this with a plain SQL query - you need to have a defined set of tables that your query is based on. The fact that your current implementation queries from whatever table is named by tablename from the first result-set means that to get this all in one query, you will have to restructure your data. You have to know what tables you're querying from rather than having it dynamic.
If the reason for these different tables is the different information stored in each requiring different record (column) structures, you might want to look into Key/Value pair storage in a large table. Once you combine the dynamically named ones into a single location you can integrate your two queries together.