Problems with division using a constant in another table - mysql

I am displaying recorded values of pressure.
I always store pressure as PSI in my database, knowing that I can convert it to BAR by dividing by 14.5
So, I have a table called configuration and one called measurements and I want so say
SELECT pressure DIV my_db.configuration.conversion_factor AS pressure FROM my_db.measurements WHERE ... and my front-end s/w will set my_db.configuration.conversion_factor to either 1 or 14.5 as appropriate.
But I am getting an error unknown column 'my_db.configuration.conversion_factor' in 'filed list'.
Since I am cut/pasting, I doubt that it is a spelling error - so what is wrong with my query?
[Update]
#JimGarrison set me on the correct path. What I needed was
SELECT pressure DIV (SELECT conversion_factor FROM my_db.configuration WHERE 1) AS pressure FROM my_db.measurements WHERE ...
Note: I add that WHERE 1 for anyone reading this question in future; I only have a single row in the configuration table, so I don't need a WHERE - but you might ..
Thanks, Jim

You can't refer to a field in a second table like that. my_db.configuration is a table with rows and columns. How does SQL know which row you want to use?
What I think you're looking for is
select pressure div (select conversion_factor from my_db.configuration where <???>=<???>) ...
where <???> is where you'd put the key column name and value for the entry you want to use from the conversion_factor table.

You have to list all the tables you want to reference in a FROM clause — in this case, the FROM clause.
SELECT pressure DIV my_db.configuration.conversion_factor AS pressure
FROM my_db.measurements
CROSS JOIN my_db.configuration
WHERE ...
The CROSS JOIN is used assuming there's just one row in your configuration table. It doesn't require a join condition.
Or you can use a sub-select as Jim Garrison suggests in his answer. It's probably cleaner. But note that he referenced the configuration table in a FROM clause.

Related

Extremely basic SQL Misunderstanding

I'm preparing for an exam in databases and SQL and I'm solving an exercise:
We have a database of 4 tables that represent a human resources company. The tables are:
applicant(a-id,a-name,a-city,years-of-study),
job(job-name,job-id),
qualified(a-id,job-id)
wish(a-id,job-id).
the table applicant represents the table of applicants obviously. And jobs is the table of available jobs. the table qualified shows what jobs a person is qualified for, and the table wish shows what jobs a person is interested in.
The question was to write a query that displays for each job-id, the number of applicants that are both qualified and interested to work in.
Here is the solution the teacher wrote:
Select q1.job_id
, count(q1.a_id)
from qualified as q1
, wish as w1
Where q1.a_id = w1.a_id
and q1.job_id = w1.job_id
Group by job_id;
That's all well and good, I'm not sure why we needed that "as q1" and "as w1", but i can see why it works.
And here is the solution I wrote:
SELECT job-id,COUNT(a-id) FROM job,qualified,wish WHERE (qualified.a-id=wish.a-id)
GROUP BY job-id
Why is my solution wrong? And also - From which table will it select the information? Suppose I write SELECT job-id FROM job,qualified,wish. From which table will it take the information? because job-id exists in all 3 of these tables.
You can only refer to tables mentioned in the FROM clause. If it's ambiguous (because more than one has a column of the same name) then you need to be explicit by qualifying the name. Usually the qualifier is an alias but it could also be the table name itself if an alias wasn't specified.
There's a concept of a "natural join" which joins tables on common column(s) between two tables. Not all systems support that notation but I think MySQL does. I believe these systems usually collapse the joined pairs into a single column.
select q1.job_id, count(q1.a_id) from qualified as q1, wish as w1
where q1.a_id = w1.a_id and q1.job_id = w1.job_id
group by job_id;
I don't think I've worked on any systems that would have accepted the query above because the grouping column would have been strictly unclear even though the intention really is not. So if it truly does work correctly on MySQL then my guess is that it recognizes the equivalence of the columns and cuts you some slack on the syntax.
By the way, your query appears to be incorrect because you only included a single column in a join that requires two columns. You also included a third table which means that your result will effectively do a cross join of every row in that table. The grouping is going to still going to reduce it to one row per job_id but the count is going to be multiplied by the number of rows in the job table. Perhaps you added that table thinking it would hurt to add it just in case you need it but that is not what it means at all.
Your query will list non-existing jobs in case the database has orphan records in applicant and qualified, and might also omit jobs that have no qualified and willing candidates.
I'm not exactly sure, because I have no idea if there's any database that will accept COUNT(a-id) when there's no information about the table from which to take this value.
edit: Interestingly it looks like both of these problems are shared by both of the solutions, but shawnt00 has a point: your solution makes a huge pointless cartesian of three tables: see it without the group by.
My current best guess for a working answer would therefore be http://sqlfiddle.com/#!9/09d0c/6

How to implement MySQL SET concept with over 64 members?

What is the best way to replicate the behaviour of a MySQL SET col type, with over 64 members?
I need to do what I would naturally do with a MySQL SET with around 85 different options. (The limit is 64.) What would be the best way to implement this?
I've looked at this question, which suggests a JOIN, but my members are only 6-char strings, is the most efficient way really to create an entire new, 1-column table of these members (I'll call it table 2), and then a third table of 2 cols linking an id from table 1 (where I would have created my SET column) and table 2?
Normalise into a second table that uses an ENUM:
From a single-table design like this:
ID, ..., Set_Col
to these:
Table1: ID, ...
Table2: Table1_ID, Enum_Col
You can then have a zero-or-more relationship from your Table1 PK (ID) to values in your "set", which is now not a set but a normalised ENUM value. You get the space benefits of a SET or ENUM, the multiplicity of a SET, but you overcome the 64 member limit of SET.
Since you already have those 6-char strings, there will be cases in the future when you will have to put them in a result set, so I would put them into a separate table and use the "JOIN + connection table" approach.
If there were no strings given for the elements of set, then I would implement an array of booleans in SQL. There are multiple solutions to do this, check out this SO question.

MySQL CONCAT '*' symbol toasts the database

I have a table used for lookups which stores the human-readable value in one column and a the same text stripped of special characters and spaces in another. e.g., the value "Children's Shows" would appear in the lookup column as "childrens-shows".
Unfortunately the corresponding main table isn't quite that simple - for historical reasons I didn't create myself and now would be difficult to undo, the lookup value is actually stored with surrounding asterisks, e.g. '*childrens-shows*'.
So, while trying to join the lookup table sans-asterisks with the main table that has asterisks, I figured CONCAT would help me add them on-the-fly, e.g.;
SELECT *
FROM main_table m
INNER JOIN lookup_table l
ON l.value = CONCAT('*',m.value,'*')
... and then the table was toast. Not sure if I created an infinite loop or really screwed the data, but it required an ISP backup to get the table responding again. I suspect it's because the '*' symbol is probably reserved, like a wildcard, and I've asked the database to do the equivalent of licking its own elbow. Either way, I'm hesitant to 'experiment' to find the answer given the spectacular way it managed to kill the database.
Thanks in advance to anyone who can (a) tell me what the above actually did to the database, and (b) how I should actually join the tables?
When using CONCAT, mysql won't use the index. Use EXPLAIN to check this, but a recent problem I had was that on a large table, the indexed column was there, but the key was not used. This should not bork the whole table however, just make it slow. Possibly it ran out of memory, started to swap and then crashed halfway, but you'd need to check the logs to find out.
However, the root cause is clearly bad table design and that's where the solution lies. Any answer you get that allows you to work around this can only be temporary at best.
Best solution is to move this data into a separate table. 'Childrens shows' sounds like a category and therefore repeated data in many rows. This should really be an id for a 'categories' table, which would prevent the DB from having to run CONCAT on every single row in the table, as you could do this:
SELECT *
FROM main_table m
INNER JOIN lookup_table l
ON l.value = m.value
/* and optionally */
INNER JOIN categories cat
ON l.value = cat.id
WHERE cat.name = 'whatever'
I know this is not something you may be able to do given the information you supplied in your question, but really the reason for not being able to make such a change to a badly normalised DB is more important than the code here. Without either the resources or political backing to do things the right way, you will end up with even more headaches like this, which will end up costing more in the long term. Time for a word with the boss perhaps :)

Do i really need to include table names or AS in JOINS if columns are different?

I noticed te other day I can joins in mysql just as easily by doing,
SELECT peeps, persons, friends FROM tablea JOIN tableb USING (id) WHERE id = ?
In stead of using,
SELECT a.peeps, a.persons, b.friends FROM tablea a JOIN tableb b USING (id) WHERE id = ?
It only works if there is no matching column names, why should I do the second rather than the first?
No, you don't need to, but in my humble opinion you really should. It's almost always better in my experience to be explicit with what you're trying to do.
Consider the feelings of the poor guy (or girl) who has to come behind you and try to figure out what you were trying to accomplish and in which tables each column resides. Explicitly stating the source of the column allows one to look at the query and glean that information without deep knowledge of the schema.
Query 1 will work (as long as there are no ambiguous column names).
Query 2 will
be clearer
be more maintainable (think of someone who doesn't know the database schema by heart)
survive the addition of an ambiguous column name to one of the tables
So, don't be lazy because of that pitiful few saved keystrokes.
It's not necessary if you have no duplicate column names. If you do, the query will fail.

Run Query for each result of another query - Access

I am trying to use the results of another query to use as a criteria for another. In my specific example, I might have four houses that are 'A', 'B', 'C', 'D' (the unique values of a field in a table called Homes).
I want to go through another query and say for each house type, what percent of residents (in Residents table) are married, which I want to do by using Count() to count the number for each Home type.
Do I need to loop through the results using VBA? Asking on a higher level, is there a way to use the results from a query as inputs into another - more than just limit the results of the new query to the results of the prior query?
Edit:
In semi-pseudo code:
For each (result of previous query) Do
New query WHERE field1 = (row of previous query)
End Do
What I am trying to ask, is there a way to accomplish this in Access using SQL? Or is this something that has to be done in VBA?
I know that if it can be done in SQL that would be the best performing and best practice, but I'm relatively inexperienced in SQL and online resources aren't always helpful because Access has it's own particular flavor of SQL.
Since you are using VBA to run this, you can loop through your recordsets and yes you can use a value from one query in the next query. There are alot of resources out there to help.
VBA: Working with RecordSets
Looping through Record Sets
Code through all records
To answer your general question, yes there is. You can do a nested query i.e. select column a from table a where column a = (select column b from table b where column b=x)
You can go as many levels deep as you want, but the caveat is the nested query can only return one column and with a specific answer set. You can also use select statements as your columns i.e
select (select column b from table b) col b from table a ..... Not the exact syntax but I would have to dig out some examples from an old project to find that.
Nested queries are useful, but for the level of precision you are looking for, a stored procedure or a view is probably a better option. Just for ease of use, I would look at creating a view of the data that you want and then querying from that to start with. More flexible than a nested query.
You need to join two tables using a common column and then get your specific column from any of the table
SELECT A.REQUIRED_FIELD from TABLEA AS A
INNER JOIN TABLEB AS B ON A.FOREIGN_KEY=B.FOREIGN_KEY
WHERE CONDITION