In my db I have phone numbers like 094-144-54
But I have to find them only with 09414454
Right now I've got this:
0[^[:digit:]]*9[^[:digit:]]*4[^[:digit:]]*1[^[:digit:]]*4[^[:digit:]]*4[^[:digit:]]*5[^[:digit:]]*4
It works, but is there a shorter way to write this? I know \D but I think it doesn't work with the MySQL RegtExp implementation.
Also, how do I select several rows like this?
SELECT number FROM tb1 WHERE ((number REGEXP ' ... '), (number REGEXP ' ... '), ... );
This doesn't work.
I tested this a pure digit number starting with 0 and ended by 4:
SELECT number FROM tb1 WHERE (number REGEXP '^0[[:digit:]]*4$');
Or a pure digit number as this:
SELECT number FROM tb1 WHERE (number REGEXP '^[[:digit:]]+$');
This php to reform an input string "09414454":
<?php
$strPhoneNo = "09414454";
$strPhoneNo = substr(chunk_split($strPhoneNo, 3, '\-'), 0, -2);
//
// => "094\-144\-54"
//
$strSQL = "SELECT number FROM tb1 WHERE (number REGEXP '^$strPhoneNo$');";
//
echo "<pre>\n";
echo $strSQL;
echo "</pre>\n";
//
// $strSQL:
// SELECT number FROM tb1 WHERE (number REGEXP '^094\-144\-54$');
//...
?>
Related
I have a table with fullname column. I want to make a query for finding a person via his last name but his last name is in the full name column.
Would it matter if it accidentally returned someone whose first name matched your query?
A simple query would be:
SELECT *
FROM TABLE
WHERE fullname LIKE '%insertlastname%'
If you want to define the last name as the name after the last space:
SELECT substring_index(fullname, ' ', -1) as lastname
FROM TABLE
WHERE lastname='insertlastname'
Two suboptimal answers, but some answers at least.
enter code here You can use this if you want to fetch by query:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX( `fullname` , ' ', 2 ),' ',1) AS b,
SUBSTRING_INDEX(SUBSTRING_INDEX( `fullname` , ' ', -1 ),' ',2) AS c FROM `users` WHERE `userid`='1'
But you can also try by PHP to fetch last name. You just use explode function to fetch last name.
Exm:
$full_name = "row moin";
$pieces = explode(" ", $fullname);
echo $first_name = $pieces[0]; // row
echo $last_name = $pieces[1]; // moin
A simple answer for this is like this suppose we have a name
Charles Dickens
:
SELECT * FROM TABLE_NAME WHERE SUBSTRING_INDEX(FULLNAME,' ',-1) like '%Dickens';
Actually in my case I need to select street number from a address string, which means if the string is '1234 dummy789 road', I only want to get '1234', not '1234789' Another example is 'Plot 111 dummy 1220' then i want only '111'. and if the string is '111/2 dummy' then i want to get '111/2'
I tried following:
SELECT CASE WHEN substr(address , 1, 1) between '0' and '9'
THEN substr(address , 1, 1)
ELSE 'False'
END as add
from test
<?php
$ab = "1225584454 red 1555 blue";
$result = explode(" ", $ab, 2);
print_r($result);
?>
in this case this will gives you first string in your variable.
Assuming that you have civil number followed by space and street name I would suggest the following:
Put WHERE statement with REGEXP to get those, which start with digit-followed-by-space. And in returned field get only numeric portion with substring.
Something like this:
SELECT SUBSTRING(address, 0, LOCATE(' ', address)) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;
Correction:
SELECT TRIM(LEFT(address, LOCATE(' ', address))) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;
I have the following MySQL query which works
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
Now there is no ORDER BY and if:
- bigDataField contains "one" this field is shown
- bigDataField contains "one two" this field is shown aswell
now it depends on the id which one of those is shown first, but I want the one with the more matches to be shown first!
I tried with
SUM(
CASE WHEN bigDataField REGEXP "one|two"
THEN 1
ELSE 0 END
) AS matches
But that does not work. Can anyone help me. I think the best would be as the title says to count the matching charachters from the REGEXP. If there are other ways please explain.
The REGEXP is a user input, so, I'm trying to implement a small search over a small Database.
This is theoretical whilst sqlfiddle is down but you might have to split the REGEXP into two so you can count the matches. REGEXP will return either a 0 or 1. Either it matched or didn't. There's no support for finding how many times it was matched in a string.
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
ORDER BY (bigDataField REGEXP "one" + bigDataField REGEXP "two") DESC
There is no way to count the amount of matches on a regex. What you can do is match them separately and order by each of those matches. EG:
SELECT *,
CONCAT( office, ' ', contactperson ) AS bigDataField
FROM webcms_mod_references
HAVING bigDataField REGEXP "one|two"
ORDER BY
CASE WHEN bigDataField REGEXP "one" AND bigDataField REGEXP "two" THEN 0
ELSE 1 -- The else should catch the "two" alone or the "one" alone because of the filtering
END
Of course, you can use a LIKE here too but maybe your regex are more complex than that :)
When I want to count some substring I do replace and "-" the length, example:
SELECT (
LENGTH('longstringlongtextlongfile') -
LENGTH(REPLACE('longstringlongtextlongfile', 'long', ''))
) / LENGTH('long') AS `occurrences`
I think this is an elegant solution for a problem of counting how many times 'long' appears inside provided 'string'
This is not especially the answer to this question, but I think strongly attached to it... (And I hope, will help someone, who cames from google, etc)
So if you use PHP (if not, may dont keep reading ...), you can build the query with that, and in this case, you can do this (about #Moob great answer):
function buildSearchOrderBy(string $regex, string $columName, string $alternateOrderByColumName): string
{
$keywords = explode ('|', $regex);
if (empty ($keywords)) {
return $alternateOrderByColumName;
}
$orderBy = '(';
$i = 0;
foreach ($keywords as $keyword) {
$i++;
if ($i > 1) $orderBy .= " + ";
$orderBy .= "IF((" . $columName . " REGEXP '" . $keyword . "')>0, " . (100 + strlen($keyword)) . ", 0)";
}
$orderBy .= ')';
return $orderBy;
}
So in this case every match worth 100 + so many scores, what the numbers of the characters in the current keyword. Every match starting from 100, because this ensure the base, that the first results will be these, where the total score originate from the more matches, but in proportionally worth more a longer keyword in any case.
Builded to one column check, but I think you can update easy.
If copied to your project, just use like this (just an example):
$orderBy = buildSearchOrderBy($regex, 'article.title', 'article.created');
$statement = "SELECT *
FROM article
WHERE article.title REGEXP '(" . $regex . ")'
ORDER BY " . $orderBy . " DESC"
;
There are two columns in a MySQL table: SUBJECT and YEAR.
I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.
How can I do this? Is it possible to use a simple operator like +?
You can use the CONCAT function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET #rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(#rn := #rn+1,3,'0'))
FROM `table`
You can use mysql built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change field name as your requirement
then the result is
and if you want to concat same field using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
then this is output
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
In query, CONCAT_WS() function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
I have two columns:
prenom and nom so to concatenate into a column with name chauffeur_sortant I used this script:
SELECT date as depart, retour, duree_mission, duree_utilisation, difference, observation, concat( tb_chaufeur_sortant.prenom, ' ', tb_chaufeur_sortant.nom) as chauffeur_sortant, concat(tb_chaufeur_entrant.prenom, ' ', tb_chaufeur_entrant.nom) as chauffeur_entrant
FROM tb_passation
INNER JOIN tb_vehicule
ON tb_vehicule.id = tb_passation.id_vehicule
INNER JOIN tb_chaufeur_sortant
ON tb_chaufeur_sortant.id = tb_passation.id_sortant
INNER JOIN tb_chaufeur_entrant
ON tb_chaufeur_entrant.id = tb_passation.id_entrant WHERE tb_vehicule.id = '';
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
is it at all possible to do this?
for instance if i had
$row['price']
and the value of this was 15000
I would like it to show as 15,000 but I dont have a clue about how to go about this?
thanks for any help.
So, you want to FORMAT your data? How about using the FORMAT function?
FORMAT(X,D)
Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. D should be a constant value.
mysql> SELECT FORMAT(12332.123456, 4);
-> '12,332.1235'
mysql> SELECT FORMAT(12332.1,4);
-> '12,332.1000'
mysql> SELECT FORMAT(12332.2,0);
-> '12,332'
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format
EDIT: Sample query
As opposed to the SELECT * people use (too often), slightly modify your queries.
SELECT id, fullName, position, FORMAT(pay, 0) as pay
FROM Employees WHERE lastName = 'Rubble';
Try this:
$row['price'] = 15000;
echo substr($row['price'], 0, -3) . ',' . substr($row['price'], -3);
echo substr($row['price'], 0, -3); // == 15
echo substr($row['price'], -3); // == 000
The 0 is the start position of the string. The -15 is the negative end position of the string.
http://at2.php.net/manual/en/function.substr.php
If you'd like to do the formatting in MySQL then you can use the FORMAT() function: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format
From PHP, you can use number_format:
$formatted = number_format($row['price']);
This will add a comma between every group of thousands. If you also want to format your price with a dot and two decimal places, use this:
$formatted = number_format($row['price'], 2);