MySQL WHERE clause not working after CSV import - mysql

I have a problem with a MySQL WHERE clause. I think I know what the problem is, just not how to fix it.
I have a database with student timetable information and I'm matching this against a table with student information. The student information has been imported into the database from a CSV (utf-8) file, the other information was just inserted into the database with "normal" INSERT queries.
The WHERE clause is simple and looks like this:
WHERE gpu_timetable.cls_name =
(SELECT cls_name FROM gpu_students WHERE std_number = 123441 LIMIT 1)
Its matching the cls_name (class name) from the timetable against the class name from the students table. Like I said the data is from different sources but looks to be the same. For example when I remove the SELECT query and use this string ('LV6A') the code works.
The collation on both of the fields is *utf8_general_ci*, I also tried TRIM() but no success, the same for replacing the operator = with LIKE.
Did I do something wrong when importing the student information or is there another function similar to TRIM() that can fix this weird problem?

Your simplified query must be:
SELECT * FROM gpu_timetable INNER JOIN gpu_students ON gpu_timetable.cls_name = gpu_students.cls_name WHERE gpu_students.std_number = 123441
Your should always have tablename.fieldname while using JOIN queries.

Related

Can SqlAlchemy's array_agg function accept more than one column?

I want to return arrays with data from the entire row (so all columns), not just a single column. I can do this with a raw sql statement in Postgresql,
SELECT
array_agg(users.*)
FROM users
WHERE
l_name LIKE 'Br%'
GROUP BY f_name;
but when I try to do it with SqlAlchemy, I'm getting
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'InstrumentedAttribute'
For example, when I execute this query, it works fine
query: Query[User] = session.query(array_agg(self.user.f_name))
But with this I get arrays of rows with only one column value in them (in this example, the first name of a user) whereas I want the entire row (all columns for a user).
I've tried explicitly listing multiple columns, but to no avail. For example I've tried this:
query: Query[User] = session.query(array_agg((self.user.f_name, self.user.l_name))))
But it doesn't work. I get the above error message.
You could use Python feature unpack for create
example = [func.array_agg(column) for column in self.example.__table__.columns]
query = self.dbsession.query(*attach)
And after join results

how to include hard-coded value to output from mysql query?

I've created a MySQL sproc which returns 3 separate result sets. I'm implementing the npm mysql package downstream to exec the sproc and get a result structured in json with the 3 result sets. I need the ability to filter the json result sets that are returned based on some type of indicator in each result set. For example, if I wanted to get the result set from the json response which deals specifically with Suppliers then I could use some type of js filter similar to this:
var supplierResultSet = mySqlJsonResults.filter(x => x.ResultType === 'SupplierResults');
I think SQL Server provides the ability to include a hard-coded column value in a SQL result set like this:
select
'SupplierResults',
*
from
supplier
However, this approach appears to be invalid in MySQL b/c MySQL Workbench is telling me that the sproc syntax is invalid and won't let me save the changes. Do you know if something like what I'm trying to achieve is possible in MySQL and if not then can you recommend alternative approaches that would help me achieve my ultimate goal of including some type of fixed indicator in each result set to provide a handle for downstream filtering of the json response?
If I followed you correctly, you just need to prefix * with the table name or alias:
select 'SupplierResults' hardcoded, s.* from supplier s
As far as I know, this is the SQL Standard. select * is valid only when no other expression is added in the selec clause; SQL Server is lax about this, but most other databases follow the standard.
It is also a good idea to assign a name to the column that contains the hardcoded value (I named it hardcoded in the above query).
In MySQL you can simply put the * first:
SELECT *, 'SupplierResults'
FROM supplier
Demo on dbfiddle
To be more specific, in your case, in your query you would need to do this
select
'SupplierResults',
supplier.* -- <-- this
from
supplier
Try this
create table a (f1 int);
insert into a values (1);
select 'xxx', f1, a.* from a;
Basically, if there are other fields in select, prefix '*' with table name or alias

Naming columns from other tables

Just a quick question about naming columns that come from other tables, below i have the tables put in the SQL statement but after it I put an abbreviated version "MO" is this correct/ will this work in all situations or should i just stick to the full version like module.mod_code?
SELECT MO.MOD_CODE, MO.MOD_NAME, MO.ECTS_UNITS,MO.DESCRIPTION
FROM MODULE MO, SYLLABUS SY, PROGRAMME PR
WHERE MO.MOD_CODE = SY.MOD_CODE
AND SY.PROG_CODE = PR.PRO_CODE
AND PR.NFQ_LEVEL = ‘LEVEL 9’
AND MO.DESCRIPTION LIKE ‘%RESEARCH%’ OR DESCRIPTION LIKE ‘%QUALATIVE%’ OR DESCRIPTION LIKE ‘%QUANTITATIVE%’;
Thanks :)
If I understood correctly, you're trying to reference columns using the table alias, and are wondering if there is any difference in using MO.[column] and module.[column]?
If that is the case, it is preferred to use the table alias to reference the column. This is because you may join back to the same table to retrieve a different subset of data. If you do this, you will need to define which set you want the data to come from.
Module AS M ---- Programme AS P ------ Module AS SUBM
You cannot stick to the full version. Once you have given a table or subquery an alias, that is the name of that object in the scope of the query. Actually, what happens is that the table name becomes the table alias, so you can use it for qualifying columns in the table.
You should also learn proper explicit JOIN syntax. I am also guessing that you are missing parentheses on your WHERE clause:
SELECT MO.MOD_CODE, MO.MOD_NAME, MO.ECTS_UNITS,MO.DESCRIPTION
FROM MODULE MO JOIN
SYLLABUS SY
ON MO.MOD_CODE = SY.MOD_CODE JOIN
PROGRAMME PR
ON SY.PROG_CODE = PR.PRO_CODE
WHERE PR.NFQ_LEVEL = 'LEVEL 9' AND
(MO.DESCRIPTION LIKE '%RESEARCH%' OR
MO.DESCRIPTION LIKE '%QUALATIVE%' OR
MO.DESCRIPTION LIKE '%QUANTITATIVE%'
);
If you attempted something like SELECT MODULE.MOD_CODE in this query, it would return an error, because the table alias MODULE is not assigned to any object.

phpmyadmin SQL query multiple tables

I have two tables.
(1) compressors
(2) crankcase_heaters
I'm trying to create a SQL query to do:
Select the compressor.VOLTAGE and compressor.WATT of each compressor.PART_NUMBER
Find the crankcase_heater.PARTNO that has the same voltage and watts.
Add that value into a new field on the compressor table called "CRANKHTR"
Essentially this query will reproduce my compressors table but will have another 'column' called "CRANKHTR".
I'm completely lost on where to even start with this. I tried using the phpmyadmin SQL Query builder but i have no idea where to begin.
Without seeing the exact data structure, it sounds like you need a simple INNER JOIN:
SELECT
`cp`.`VOLTAGE`,
`cp`.`WATT`,
`ch`.`PARTNO` as CRANKHTR
FROM
`compressor` cp
INNER JOIN `crankcase_heaters` ch ON ch.VOLTAGE = cp.VOLTAGE AND ch.WATT = cp.WATT

Pivoting Concept

Hiii,
I have a Database design as:
Table File (FileID, Name, Details)
Table Attributes (AttID, AttName, AttType)
Table AttValues (FileID, AttID, AttValue)
Till the runtime, it is not known how many Attributes are in a File and of what names.
And I want to display after insertion at Frontend in a manner like like:
FileID, FileName, Details, (Rows of Attribute Table as Column here).
i.e.,
Can anybody provide me a piece of code in Java or in MySQL to achieve this Pivoting Result.
Highly thanks full for your precious time.
Or is there any other better way to store data, So that I can get the desired result easily.
This requires two queries. First select the File:
SELECT * FROM File WHERE (...)
Then, fetch the Attributes:
SELECT *
FROM AttValues
JOIN Attributes ON (Attributes.AttId = AttValues.AttId)
WHERE FileId = $id
The latter query will provide you with one row per Attribute, which you can programmatically pivot for display on your frontend:
foreach(row in result) {
table.AddColumn(Header = row['AttName'], Value = row['AttValue']);
}
Adapt to your local programming environment as needed.
Of course, this only works for a single File or Files with the same attributes. If you want to display multiple files with different Attributes you can instead prefetch all AttNames:
SELECT Attributes.AttId, Attributes.AttName
FROM Attributes
JOIN AttValues ON (Attributes.AttId = AttValues.AttId)
WHERE FileId IN ( $list_of_ids )
Then load the values like this:
SELECT *
FROM AttValues
WHERE FileId IN ( $list_of_ids )
and use a local associative array to map from AttIds to column indexes.
As a final optimisation, you can combine the last two queries into an OUTER JOIN to avoid the third round trip. While this will probably increase the amount of data transferred, it also makes filling the table easier, if your class library supports named columns.
I answered a similar question recently: How to pivot a MySQL entity-attribute-value schema. The answer is MySQL-specific, but I guess that's OK as the question is tagged with mysql.