I am trying to query a table in mysql based on the length of a string in a specific column. I know mysql has a function called LENGTH(), but that returns the length of the string. I want to be able to pull data based on the result of the LENGTH() function.
Example:
SELECT * table WHERE LENGTH(word) = 6
of course that does not work. I read through http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function%5Flength but could not find anything to help me.
yes I could make something in PhP to accomplish this, but I would like to do it at the query level.
Any help?
Try:
SELECT *
FROM table
WHERE LENGTH(RTRIM(word)) = 6
I believe you wanted to use query SELECT * FROM tableName WHERE LENGTH(word) = 6; (assuming that the word is name of column in tableName).
This is very unfortunate solution on large tables, you should create new column and use UPDATE tableName SET wordLength = LENGTH( word).
Related
I have tried to select something with SQL, and I've a problem with it.
What I want:
SQL SELECT * FROM table WHERE ? = '5';
Select everything which = 5, BUT not specify from which column.
Example:
From this ""database"", you should receive the 1st and the last row.
Is that possible?
You have to list the columns but you can use in. The where clause looks like:
where 5 in (price, height)
Note: This assumes that the columns have the same type. You could get type conversion errors if they are not.
Also, given the names of the column and the data, I assume that the columns are stored as numbers. Hence, I dropped the single quotes around 5. If they are really strings, then use the single quotes.
you need to add a condition to your query with or keyword so if any of them match the row will be shown as a result
SELECT * FROM tablename WHERE price =5 or height= 5
better you list your columns by name instead of using * after SELECT
I have a table and in that I want to sort a column in that table. But I’m unable to get the sorted order because there are different kinds of characters in the first place of the string. Some of them have horizontal tab, some of them have spaces, and some of them are empty. I have tried trim method but it doesn’t work for me. I have nearly 200000 records in that table. I cant update the table. I need a select query which should give the result neglecting all the unnecessary things and should sort the columns.
I think this might work
SELECT *
FROM table_name
ORDER BY IF(coloum_name LIKE "_%", substr(coloum_name, 1), coloum_name);
Explanation:
We use the IF function to strip the first character from the beginning of the string before returning the string to the ORDER BY clause. For more complex rules we could create a user-defined function and place that in the ORDER BY clause instead. Then you would have ...ORDER BY MyFunction(coloum_name)
For SQL Server, do this:
SELECT *
FROM table_name
ORDER BY CASE WHEN coloum_name LIKE "_%" THEN substr(coloum_name, 1) ELSE coloum_name END
This case is similar to: S.O Question; mySQL returns all rows when field=0, and the Accepted answer was a very simple trick, to souround the ZERO with single quotes
FROM:
SELECT * FROM table WHERE email=0
TO:
SELECT * FROM table WHERE email='0'
However, my case is slightly different in that my Query is something like:
SELECT * FROM table WHERE email=(
SELECT my_column_value FROM myTable WHERE my_column_value=0 AND user_id =15 LIMIT 1 )
Which in a sense, becomes like simply saying: SELECT * FROM table WHERE email=0, but now with a Second Query.
PLEASE NOTE: It is a MUST that I use the SECOND QUERY.
When I tried: SELECT * FROM table WHERE email='( SELECT my_column_value FROM myTable WHERE my_column_value=0 LIMIT 1 )' (Notice the Single Quotes on the second query)
MySql SCREAMED Errors near '(.
How can this be achieved
Any Suggestion is highly honored
EDIT1: For a visual perspective of the Query
See the STEN_TB here: http://snag.gy/Rq8dq.jpg
Now, the main aim is to get the sten_h where rawscore_h = 0;
The CURRENT QUERY as a whole.
SELECT sten_h
FROM sten_tb
WHERE rawscore_h = (
SELECT `for_print_stens_rowscore`
FROM `for_print_stens_tb`
WHERE `for_print_stens_student_id` =3
AND `for_print_stens_factor_name` = 'Factor H' )
The result of the Second Query can be any number including ZERO.
Any number from >=1 Works and returns a single corresponding value from sten_h. Only =0 does not Work, it returns all rows
That's the issue.
CORRECT ANSWER OR SOLUTION FOR THIS
Just in case someone ends up in this paradox, the Accepted answer has it all.
SEE STEN_TB: http://snag.gy/Rq8dq.jpg
SEE The desired Query result here: http://snag.gy/wa4yA.jpg
I believe your issue is with implicit datatype conversions. You can make those datatype conversions explicit, to gain control.
(The "trick" with wrapping a literal 0 in single quotes, that makes the literal a string literal, rather than a numeric.)
In the more general case, you can use a CAST or CONVERT function to explicitly specify a datatype conversion. You can use an expression in place of a column name, wherever you need to...
For example, to get the value returned by my_column_value to match the datatype of the email column, assuming email is character type, something like:
... email = (SELECT CONVERT(my_column_value,CHAR(255)) FROM myTable WHERE ...
or, to get the a literal integer value to be a string value:
... FROM myTable WHERE my_column_value = CONVERT(0,CHAR(30)) ...
If email and my_column_value are just indicating true or false then they should almost certainly be both BIT NOT NULL or other two-value type that your schema uses for booleans. (Your ORM may use a particular one.) Casting is frequently a hack made necessary by a poor design.
If it should be a particular user then you shouldn't use LIMIT because tables are unordered and that doesn't return a particular user. Explain in your question what your query is supposed to return including exactly what you mean by "15th".
(Having all those similar columns is bad design: rawscore_a, sten_a, rawscore_b, sten_b,... . Use a table with two columns: rawscore, sten.)
Is there any way to do something like :
SELECT * FROM TABLE WHERE COLUMN_NUMBER = 1;
?
No, you can't. Column order doesn't really matter in MySQL. See the below question for more details.
mysql - selecting values from a table given column number
If your table has a column named COLUMN_NUMBER and you want to retrieve rows from the table where that column contains a value of '1', that query should do the trick.
I suspect that what you are trying to do is reference an expression in the select list with an alias. And that is not supported. An expression in the WHERE clause that references a column must reference the column by name.
We can play some tricks with inline views, to give an alias to an expression, but this is not efficient in terms of WHERE predicates, because of the way MySQL materializes a derived table. And, in that case, its a name given to the column in the inline view that has to be referenced in the outer query.
How I did it:
I'm trying to take (last 3 values of) column number 4 in sometable.
set #mydb=(SELECT DATABASE());
set #mycol=(select COLUMN_NAME from information_schema.columns where
table_schema=#mydb and table_name='sometable' and ordinal_position = 4);
SELECT Date,#mycol FROM sometable ORDER BY Date DESC LIMIT 3;
Of course, if Database name is known, first line could by whiped and #mydb replaced by real database name.
You can do this trick
Example:
$query="select * from employee";
$result=mysql_query($query);
$meta=mysql_fetch_field($result,0) // 0 is first field in table , 1 is second one ,,, etc
$theNameofFirstField=$meta->name; // this well return first field name in table
// now you can use it in other query
$seconQuery="select $theNameofFirstField from employee";
I would like to SELECT * FROM table where the first column is equal to a variable. It supposed that I don't know the column name.
I know I can do something like
SELECT * FROM table WHERE column_id = 1
But I can't compare the data.
How can I do that?
I found some solution with T-SQL but it doesn't interest me.
To be more accurate :
I'm developing an administration panel in my website where the "super" admin can directly modify the database. For that I can select a table and edit this table. But to do that, I'm using an only PHP script which showing all tables, we can select one and the script show all rows in the selected table. After that you select a row and you are redirected to a page where the problem is. This page can receive any table with only one row, so I want to SELECT the data contained in this row.
Images to understand:
The first one shows the tables.
The second shows the rows of a selected table.
The third shows (normally) the data of 1 row but in this picture we can see data of many rows.
selecto http://imageshack.us/g/135/selecto.png
I found a solution :
Try to explain:
First : I selected all form the specific table which was posted
$query="SELECT * FROM ".$_POST['table']."";
$result=mysql_query($query);
Second: I attributed to a variable the column name (which I didn't know)
while($fields=mysql_fetch_array($result))
{
$col = mysql_field_name($result,0);
$nb++;
}
Third: I selected data from the table where $col = id of the row
$sql = "SELECT * FROM ".$_POST['table']." WHERE ".$col."=".$_GET['idRow']."";
$result1=mysql_query($sql);
If you know how many columns there are, you could use this little trick here:
SELECT *
FROM (
SELECT null x1, null x2, ..., null xn
WHERE 1 = 0
UNION ALL
SELECT * FROM my_table
) t
WHERE t.x1 = something
In other databases than MySQL, renaming "unknown" columns would be even simpler, e.g. in PostgreSQL you could rename only the first column like this:
SELECT * FROM my_table t(x) WHERE x = something
If you don't know anything about the table
... you can quickly query the information_schema first:
SELECT column_name
FROM information_schema.columns
WHERE table_name = :my_table
AND ordinal_position = 1
A note on SQL injection
Please don't, DON'T do this. EVER:
$query="SELECT * FROM ".$_POST['table']."";
I've recently written an article about SQL injection. Every single vulnerability like yours will allow any script kiddie to dump your database, or worse.
The solution is to sanitize your input first. Ideally, you'll maintain a catalog of allowed table strings, compare your $_POST variable with those, and then concatenate the pre-defined table string into your SQL statement, NOT the user input.
I think you can use SHOW CREATE TABLE table_name to fetch the schema of the table. After that, you should already know every column.
In PHP you could do something like:
$col = 'users';
mysql_query("SELECT * FROM table WHERE $col = $something");