MySQL if first character is number - mysql

I am trying to write an mysql script to see if the first character is a number or not, this is what I go so far
select CASE WHEN user_id REGEXP '[0-9]+' then 1 else 0 end as user_id from table
it returns all my data as 1...the colum is a varchar, I will have user_id like this 1234 or this USER-484 or `ADMIN-464567' IS what I am trying to do possible?

So you want to display the user_id instead? Then put your regexp in the WHERE clause
select user_id from table
where
user_id REGEXP '^[0-9]+'
Also you're missing a ^ which means "at the beginning of the line"

Try this to check if starting letter/digit is a number:
select CASE WHEN user_id
REGEXP '^[0-9]+'
then 1 else 0 end as user_id
from table;
or
select CASE WHEN user_id
REGEXP '^\d+'
then 1 else 0 end as user_id
from table;
I am just wondering about your query arrangement. I thought it should be like this,
select user_id
from table
where REGEXP '^\d+' ;
But yours is actually working with the correct regex. :)
* SQLFIDDEL DEMO

Since you are missing ^ before [0-9] it matches numbers at any place in your field. By specifying ^[0-9] it means that it should BEGIN with a number. So try using '^[0-9]'

Related

MySQL Query Question to finde value in string

i have a simple (i hope its simple) question.
In my database, i have an entry like this:
Now, i need a response with true or a count if the '514' in 'error_code' is in the string 'count_alarm'. In this example it returns zero because 514 isnt in count_alarm.
I beginns the query, but i dont know how i can solve this query:
select count(*) from table where sID='56df32a1463d4387' and [if
error_code in count_alarm then True]
Somebody an idea?
Perhaps you can just use REGEXP here:
SELECT COUNT(*) AS cnt
FROM yourTable
WHERE sID = '56df32a1463d4387' AND
count_alarm REGEXP CONCAT('[[:<:]]', error_code, '[[:>:]]');
find_in_set can parse comma separated fields:
select count(*)
from your_table
where sID = '56df32a1463d4387'
and find_in_set(error_code, replace(count_alarm, '|', ',')) > 0
or use instr
where sID = '56df32a1463d4387'
and instr(count_alarm, concat('|', error_code, '|')) > 0
select count(sID) as n514 from table where sID='56df32a1463d4387'
and count_alarm like '%|514|%'
The LIKE operator searches for the pattern |514| anywhere in the value under count_alarm.
The assumption is that the first and last character of that value is this character | else 514 would not be found if it is the first or last pattern within that value.

mysql query for excluding fields

A poll result table:
ID, NAME, ANSWER char(1)
query which select Name start with 'N' but answer not have 'Y'
My try
select *
from poll
where name like "N%" AND answer NOT LIKE "Y"
It is not working
You had missing ; after the query. should be used ;
select *
from poll
where name like 'N%' AND answer NOT LIKE 'Y';

MySQL - WHERE x IN ( column)

I tried something out. Here is a simple example in SQL Fiddle: Example
There is a column someNumbers (comma-seperated numbers) and I tried to get all the rows where this column contains a specific number. Problem is, the result only contains rows where someNumbers starts with the specific number.
The query SELECT * FROM myTable where 2 in ( someNumbers ) only returns the row with id 2 and not the row with id 1.
Any suggestions? Thank you all.
You are storing data in the wrong format! You should not be storing multiple values in a single string column. You should not be storing numbers as strings. Instead, you should have a junction table with one row per id and per number.
Sometimes, you just have no choice, because someone else created a really poorly designed database. For these situations, MySQL has the function find_in_set():
SELECT *
FROM myTable
WHERE find_in_set(2, someNumbers ) > 0;
The right solution, however, is to fix the data model.
While Gordon's answer is a good one, here is a way to do this with like
SELECT * FROM myTable where someNumbers like '2,%' or someNumbers like '%,2,%' or someNumbers like '%,2'
The first like checks if your array starts with the number you are looking for (2). The second one checks if 2 is within the array and the last like tests for appearance at the end.
Note that the commas are essential here, because something like '%2%' would also match ...,123,...
EDIT: As suggested by the OP it may happen that only a single value is present in the row. Consequently, the query must check this case by doing ... someNumbers = '2'
I would suggest this query :
SELECT * FROM myTable where someNumbers like '%2%'
It will select every entry where someNumbers contains '2'
Select * from table_name where coloumn_name IN(value,value,value)
you can use it

Count how many times a word is being used per day

I have a MySQL table named "content"containing (a.o.) the fields "_date" and "text", for example:
_date text
---------------------------------------------------------
2011-02-18 I'm afraid my car won't start tomorrow
2011-02-18 I hope I'm going to pass my exams
2011-02-18 Exams coming up - I'm not afraid :P
2011-02-19 Not a single f was given this day
2011-02-20 I still hope I passed, but I'm afraid I didn't
2011-02-20 On my way to school :)
I'm looking for a query to count the number of times the words "hope" and "afraid" are being used per day. In other words, the output would have to be something like:
_date word count
-----------------------
2011-02-18 hope 1
2011-02-18 afraid 2
2011-02-19 hope 0
2011-02-19 afraid 0
2011-02-20 hope 1
2011-02-20 afraid 1
Is there an easy way to do this or should I just write I different query per term? I now have this, but I don't know what to put instead of "?"
SELECT COUNT(?) FROM content WHERE text LIKE '%hope' GROUP BY _date
Can somebody help met with the correct query for this?
I think the most easy and redable way is to make subquerys:
Select
_date, 'hope' as word,
sum( case when `text` like '%hope%' then 1 else 0 end) as n
from content
group by _date
UNION
Select
_date, 'afraid' as word,
sum( case when `text` like '%afraid%' then 1 else 0 end) as n
from content
group by _date
This approach has not the best performace. If you are looking for performance you should grouping in subquery by day, also this like condition is a performance killer. This is a solution if you only execute the query in batch mode time by time. Explain your performance requeriments for an accurate solution.
EDITED TO MATCH LAST OP REQUERIMENT
Your query is almost correct:
SELECT _date, 'hope' AS word, COUNT(*) as count
FROM content WHERE text LIKE '%hope%' GROUP BY _date
use %hope% to match the word anywhere (not only at the end of the string). COUNT(*) should do what you want.
To get multiple words from a single query, use UNION ALL
Another approach is to create a sequence of words on the fly and use it as the second table in a join:
SELECT _date, words.word, COUNT(*) as count
FROM (
SELECT 'hope' AS word
UNION
SELECT 'afraid' AS word
) AS words
CROSS JOIN content
WHERE text LIKE CONCAT('%', words.word, '%')
GROUP BY _date, words.word
Note that it will only count a single occurrence of each word per sentence. So »I hope there is still hope« will only give you 1, and not 2
To get 0 when there are no matches, join the previous result with the dates again:
SELECT content._date, COALESCE(result.word, 'no match'), COALESCE(result.count, 0)
FROM content
LEFT JOIN (
SELECT _date, words.word, COUNT(*) as count
FROM (
SELECT 'hope' AS word
UNION
SELECT 'afraid' AS word
) AS words
CROSS JOIN content
WHERE text LIKE CONCAT('%', words.word, '%')
GROUP BY _date, words.word ) AS result
ON content._date = result._date
Assuming you want to count all words and find the most used words (rather than looking for the count of a few specific words) you might want to try something like the following stored procedure (string splitting compliments of this blog post):
DROP PROCEDURE IF EXISTS wordsUsed;
DELIMITER //
CREATE PROCEDURE wordsUsed ()
BEGIN
DROP TEMPORARY TABLE IF EXISTS wordTmp;
CREATE TEMPORARY TABLE wordTmp (word VARCHAR(255));
SET #wordCt = 0;
SET #tokenCt = 1;
contentLoop: LOOP
SET #stmt = 'INSERT INTO wordTmp SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(`text`, " ", ?),
LENGTH(SUBSTRING_INDEX(`text`, " ", ? -1)) + 1),
" ", "") word
FROM content
WHERE LENGTH(SUBSTRING_INDEX(`text`, " ", ?)) != LENGTH(`text`)';
PREPARE cmd FROM #stmt;
EXECUTE cmd USING #tokenCt, #tokenCt, #tokenCt;
SELECT ROW_COUNT() INTO #wordCt;
DEALLOCATE PREPARE cmd;
IF (#wordCt = 0) THEN
LEAVE contentLoop;
ELSE
SET #tokenCt = #tokenCt + 1;
END IF;
END LOOP;
SELECT word, count(*) usageCount FROM wordTmp GROUP BY word ORDER BY usageCount DESC;
END //
DELIMITER ;
CALL wordsUsed();
You might want to write another query (or procedure) or add some nested "REPLACE" statements to further remove punctuation from the resulting temp table of words, but this should be a good start.

Specific ordering SQL Command

Say I have a table similar to:
ID Name
1 Test
2 Contest
3 Fittest
4 Testament
Is there a MySQL query I could use with ordering to allow it to display a specific word first?
For example, users are searching for the word "Test". I have a statement similar to "SELECT * FROM table WHERE NAME LIKE '%Test%'". Could I display results to show things that START with Test begin first followed by everything else, while everything is still in alphabetical order.
So output would be:
Test
Testament
Contested
Fittest
Thanks.
This will put your words that begin with Test at the top, and sort those words plus the remainder of the list in alphabetical order..
SELECT * FROM mytable
ORDER BY CASE WHEN name LIKE 'test%' THEN 0 ELSE 1 END ASC, name ASC
SELECT * FROM table
WHERE NAME LIKE '%Test%'
order by case when name like 'test%' then 0 else 1 end