Composing dynamic SELECT Statement - mysql

Some advise on this issue:
select
concat(MySourceTable,',',sid,'X',gid,'X',qid) as MySourceFieldname
from
MySchemaTable
where
SomeCriteria;
Using the upper Statement I get a list (one column only) of fieldnames.
How can I transform this to be shown in horizontal (Fields next to each other) position, separated by comma
I want to produce a 'normal" SELECT-Statement for further use.
#amixdon
Input is :
select concat('shape_survey_990113',sid,'X',gid,'X',qid) as lsfield -- <=MySourceFieldname
from shape_questions -- <=MySchemaTable i.e. kind of dictionary
where question='result' -- <=SomeCriteria
and sid=990113
and language='en'
order by lsfield;
Result of Input looks like this (e.g.)
lsfields
---------
shape_survey_990113.990113X468X729,
shape_survey_990113.990113X469X733,
shape_survey_990113.990113X470X737,
....,
Explanation: sid, gid, qid are numeric contents taken from a table that is comparable to a dictionary. This is the source system which I want to select information from (cannot be changed). It is an opensource survey tool. Within this table all information for each survey is handled (numeric value 990113 is identifiying one special survey out of many. The concat above ist the final field name that holds the answers to the questions.
The 'shape_survey_990113' is the table to select the firlds from:
This select result should look like this an can be written to some variable
(e.g. SET #MyFields =...)
shape_survey_990113.990113X235X476, shape_survey_990113.990113X235X484, shape_survey_990113.990113X235X496
..to be used in the next step to make up a real select statement like:
concat('SELECT ', #MyFields, ' FROM shape_survey_991103;')
Unfortunately i cannot upload a screenshot fort this, not enough reputation....

There's nothing sacred, and quite a bit profane, about that CONCAT(). Lose it. And lose the quoted commas. Like so.
select
MySourceTable, sid, gid, qid
from
MySchemaTable
where
SomeCriteria;
Simple as can be.

Related

Why ' ' was used in select statement

Came across this code today:
SELECT 'Overall' as Main,
wave,
country,
catg,
'' AS hw,
SUM(0) AS headwinds_sum
....
....
Can someone explain what ' ' in the above stands for?
Its not a typo as it is repeated #multiple instances.
Not a typo, no text was missed to add.
'' as hw
adds a column named hw to your select query of type varchar that contains empty strings.
Depending on how you process the resultset afterwards this can make sense.
The symbol is used to return an empty column in a result set. Users occasionally do this to match column counts in insert selects or when exporting data to Excel files and you want standard column names for capturing audit recommendations on data etc.

Select rows in SQL partially matching an input input

I would like to select rows in my table (I'm using Google Sheet for that purpose) which content is included in the string.
For example, rows included in table called Jobportal, column Test:
How to find work
Work permit
Jobs
Temporary jobs
I want to select all the rows that contain any word of my input, so if I write "i'm looking for a job", I need to select rows Jobs and Temporary jobs. If I write "where is my work?", I need to select How to find work and Work permit.
I've tried this query, but it's returning wrong/unexpected results.
select * from Jobportal where 'im looking for a job' LIKE CONCAT('%',Test,'%');
You can use regular expressions. Assuming that what the user types does not have special characters:
where test regexp replace('im looking for a job', ' ', '|')
That said, for performance you might want to consider using full text search capabilities.

Show Fields but with content

i'm trying to show fields names on a combobox, but I need only those that are not null or have blank spaces.
I all ready have the field names with this query:
SHOW FIELDS FROM model WHERE type LIKE 'varchar(15)'
Any idea about how can i do this?
Update:
I'm working with an old database who is poorly designed. I attached an image:Database Screenshot This is a tire sizes database, so i need to get the years by model who has the size captured to show them in a combo box.
You can use your current query to get the "candidate" fields, but (short of some very complicated dynamic sql) you'll need to build a separate query to determine which candidates are pertinent. Generically, something like:
SELECT SUM(IF(field1 REGEXP '[a-zA-Z0-9.]+', 1, 0) > 0 AS showField1
, SUM(IF(field2 REGEXP '[a-zA-Z0-9.]+', 1, 0) > 0 AS showField2
, ...
FROM theTable
;
Depending on what you consider "has values" the regexp string may need adjusted; learn more here: http://dev.mysql.com/doc/refman/5.7/en/regexp.html
If the table is huge (large number of rows), you may be better off querying on each field separately like this (the one above will be looking at the whole table without some sort of WHERE to reduce the rows examined):
SELECT 1 FROM theTable WHERE fieldX REGEXP '[a-zA-Z0-9.]+' LIMIT 1;
Treating having a query result as "yes" and no result as "no content".

how to skip the inverted commas when selecting a column from MySQL

There is a table with fields name, age, city and state. Now I need to select rows based on city name. The value of the column city is surrounded with ", for example "LA".
How can I write a SELECT statement for getting data based on city.
\" is the escape combination for double quotes:
SELECT * FROM mytable WHERE city = '\"LA\"';
See MySQL documentation "String Literals".
Just suggestion, if you are collecting and storing the information in the table to be queried later (ie you are in control of the input), try to clean the data up before storing it to make it easier to query?
If the input has quotes and white space, clean that before inserting the values into the table. Use programming to do this, or mySQL: TRIM() and REPLACE() to remove the characters that might make a query hard to build and then store the resulting value into the table.
Of course, if you do not have control of the input data, that is where the answers above and the challenge to a programmer begins, trying to figure out the different input possibilities and dealing with that.
SELECT *
FROM table1
WHERE city LIKE '%LA%'
or
SELECT *
FROM table1
WHERE city REGEXP '^[[:space:]]*LA[[:space:]]*$'

MySQL UNION query correct handling for 3 or more words

I've to ask your help to solve this problem.
My website has a search field, let's say user writes in "Korg X 50"
In my database in table "products" i have a filed "name" that holds "X50" and a field "brand" that hold "Korg". Is there a way to use the UNION option to get the correct record ?
And if the user enters "Korg X-50" ?
Thank you very much !
Matteo
May be you should use full-text search
SELECT brand, name, MATCH (brand,name) AGAINST ('Korg X 50') AS score
FROM products WHERE MATCH (brand,name) AGAINST ('Korg X 50')
As far as I understand you don't need UNION but something like
SELECT * FROM table1
WHERE CONCAT(field1, field2) LIKE '%your_string%'
On client side you get rid of all characters (like space, hyphen, etc) in your_string that appears in user input and cannot be in field1 or field2.
So, user input Korg X 50 as well as Korg X-50 becomes KorgX50.
you will need to get some form of searchable text.
either parse out the input for multiple key words and match each separately, or perhaps try to append them all together and match to the columns appended in the same way.
you will also need either a regex, or maybe a simpler search and replace to get rid of spaces and dashes after the append before the comparison.
in general, allowing users to search for open ended text strings is more complicated than 'what union do i use'... you will ideally also be worried about slight misspellings and capitalization, and keyword order.
you may consider pulling all keywords out from your normal record into a separate keyword list associated with each product, then use that list to perform your searches.
If you do not want to parse user input and use as it is, then you will need to use a query like this
select * from products where concat_ws(' ',brand,name) = user_input -- or
select * from products where concat_ws(' ',brand,name) like %user_input%
However, this query won't return result if user enters name "Korg X-50" and your table contains "Korg" and "X50", then you need to do some other thing to achive this. You may look at http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex however it won't be a complete solution. Look for text indexing libraries for that ex: lucene