Mysql: Conditional select / concat depending on column matches - mysql

I have a database with user details in one table and linked contact details in another table (where the contact details are stored as "content").
I am trying to make a quick search function where you can search for the name or any contact details. So you can either search for name or an email or phone (whatever is in the contact detail field).
This is what I have so far:
SELECT DISTINCT leads.id, CONCAT(first_name,' ', last_name) AS name
FROM `leads`
INNER JOIN `contact_details` ON contact_details`.`lead_id` = `leads`.`id`
WHERE ((CONCAT(first_name, last_name, content) LIKE ('%[XXX]%')));
This works fine. You can search for f ex "55" and it will return hits on f ex ph number 555-573-3222 or you can search for a name string like 'Joh' and it will match 'Johnson'.
My problem, though, is that regardless of what you are searching for, what is being returned is client name. Since this is for an autocomplete feature, this is obviously very confusing. If you start typing in 555-2 you want to see the suggestion 555-221-6362 not "John Johnson".
How can I return EITHER a phone number or email (from column "content") OR the concact first_name, ' ', last_name depending on whether the search matched a name or a contact_detail.content.
Since I am searching on first_name OR last_name, the search works well for "joh" matching "John" but obviously breaks when you search for "John Stan" for "John Stanley". Is there a Mysql way of fixing this or do I need to clean up string before and do alternative searches if there is a space (searching first_name AND last_name separately)
Any suggestions would be greatly appreciated as I have struggled with this for days now.

Charliez, per our comment conversation, the following is an example of how to do some nested if/thens as well as the break out of the where. You'll need to adjust this to met your specific needs, but should give you enough of an example that you should be able to get things working.
SELECT
IF(last_name LIKE '%JAM%',
last_name,
IF(first_name LIKE '%JAM%',
first_name,
''
)
) AS MatchedFieldText
FROM employee
WHERE
last_name LIKE '%JAM%'
OR first_name LIKE '%JAM%';

1) I don't think there is a way to have a SELECT statement return something different based on an OR. My first thought to solve this would be to return first, last, content and use some regex to determine if you should show the name or the number/content.
2) Kind of a hard problem, and I don't think I have seen a perfect solution to it. This might give you some ideas/put you on the right track.

Related

MySQL finding data if any 4 of 5 columns are found in a row

I have an imported table of several thousand customers, the development I am working on runs on the basis of anonymity for purchase checkouts (customers do not need to log in to check out), but if enough of their details match the database record then do a soft match and email the (probably new) email address and eventually associate the anonymous checkout with the account record on file.
This is rolling out this way due to the age of the records, many people have the same postal address or names but not the same email address, likewise some people will have moved house and some people will have changed name (marriage etc).
What I think I am looking for is a MySQL CASE system, however the CASE questions on Stack Overflow I've found don't appear to cover what I'm trying to get from this query.
The query should work something like this:
$input[0] = postcode (zip code)
$input[1] = postal address
$input[2] = phone number
$input[3] = surname
$input[4] = forename
SELECT account_id FROM account WHERE <4 or more of the variables listed match the same row>
The only way I KNOW I can do this is with a massive bunch of OR statements but that's excessive and I'm sure there's a cleaner more concise method.
I also apologise in advance if this is relatively easy but I don't [think I] know the keyword to research constructing this. As I say, CASE is my best guess.
I'm having trouble working out how to manipulate CASE to fit what I'm trying to do. I do not need to return the values only the account_id from the valid row (only) that matches 4 or 5 of the given inputs.
I imagine that I could construct a layout that does this:
SELECT account_id CASE <if postcode_column=postcode_var> X=X+1
CASE <if surname_column=surname_var> X=X+1
...
...
WHERE X > 3
Is CASE the right idea?
If not, What is the process I need to use to achieve the desired results?
What is [another] MySQL keyword / syntax I need to research, if not CASE.
Here is your pseudo query:
SELECT account_id
FROM account
WHERE (postcode = 'pc')+
(postal_address = 'pa')+
(phone_number = '12345678901')+
(surname = 'sn')+
(forename= 'fn') > 3

Multiple databases, possibly creating a loop?

I have the following code below...the query works, but I'm looking for a better way to search though an entire column for a specific criteria. I think my question is going to require a loop, I'm just not sure how to perform it.
The last line of code states '
Where [dbIdwWhseLC].[dbo].[tbItemTxt].[sTxt] like '%258912.pdf
The value 258912.pdf is the value in
[IDEAUrlBot].[dbo].[IDEA Project Tracker].[Filename]
I would like to try and create a method where the query reads one value in sTxt, then compares the whole column to Filename. If it finds the value, then display sTxt, if not, go to the next value in sTxt and begin searching each value in Filename.
Please let me know if you need additional information. Thanks in advance.
Select [dbIdwWhseLC].[dbo].[tbItemTxt].[nItemId]
, [sTxtType]
, [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId]
, [IDEAUrlBot].[dbo].[tbl_Urls].[sUrl]
, [sTxt]
, [Filename]
, [dbIdwWhseLC].[dbo].[tbItemTxt].[vUpdateDt]
From [dbIdwWhseLC].[dbo].[tbItemTxt]
Left Join [IDEAUrlBot].[dbo].[tbl_IDWItems] on [dbIdwWhseLC].[dbo].[tbItemTxt].[nItemid] = [IDEAUrlBot].[dbo].[tbl_IDWItems].[nItemid]
Join [IDEAUrlBot].[dbo].[tbl_Urls] on [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId] = [IDEAUrlBot].[dbo].[tbl_Urls].[nUrlId]
Join [IDEAUrlBot].[dbo].[IDEA Project Tracker] on [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId] = [IDEAUrlBot].[dbo].[IDEA Project Tracker].[UrlId]
Where [dbIdwWhseLC].[dbo].[tbItemTxt].[sTxt] like '%258912.pdf'
If I understand you correctly, it ought to be possible to do this:
select itemTxt.[nItemId]
, [sTxtType]
, idwItems.[nUrlId]
, urls.[sUrl]
, [sTxt]
, [Filename]
, itemTxt.[vUpdateDt]
From [dbIdwWhseLC].[dbo].[tbItemTxt] as itemTxt
Left Join [IDEAUrlBot].[dbo].[tbl_IDWItems] as idwItems
on itemTxt.[nItemid] = idwitems.[nItemid]
Join [IDEAUrlBot].[dbo].[tbl_Urls] as urls
on idwItems.[nUrlId] = urls.[nUrlId]
Join [IDEAUrlBot].[dbo].[IDEA Project Tracker] projTracker
on itemText.[nUrlId] = projTracker.[UrlId]
Where itemTxt.[sTxt] like '%258912.pdf' -- not sure you intend this to remain
and projTracker.[FileName] = itemTxt.[sTxt]
But that's so simple that there must be some aspect to what you're looking for that's not clear to me.
Do you want to stop searching after you find a match between [FileName] and [sTxt]? If you want to return exactly one record, you can just change the first line to
select top 1 itemTxt.[nItemId]
... and add an ORDER BY clause to the end to control how the results are sorted and therefore which one is the "top 1".
Do you need to use wildcards when matching [FileName] and [sTxt]? It's not clear to me from the description which column would have the full path (or file name) and which would have just "258912.pdf", but you could change my last line to:
itemTxt.[sTxt] like ('%' + projTracker.[FileName])
If you need something more complex, like the first record from itemTxt.[sTxt] that matches projTracker.[FileName] for every record in projTracker, please say so in the comments.
If none of this is along the lines of what you need, you'll need to elaborate on what it is you do need. Please add more detail to your question, such as an example of what the output should look like or what you plan to do with it.

SQL\ HTML Databases

I was actually doing somthing else and came accross this intresing W3schools tutorial/ section in relation to SQL databases (its a curiousity killed the cat thing more then anything)
The page link where my question comes from is as follows
http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where
the example lists all records that include mexico in the countrys catagorie
I can for instance change this to spain and all entrys with spain are filterd through.
The question I have is, it seems very unlikely to me that an end user is going to type out the entire code
SELECT * FROM Customers
WHERE Country='Mexico';
everytime they want too search a city (this example thus being mexico). I'm presuming we can get the city name inserted from a textbox, but ive looked can cant fand any examples on how to do this?
Try this:
SELECT * FROM Customers where <Column> like '%MEXICO%';
'%' is the wildcard. So you will find:
" MEXICO"
"MEXICO City"
"MX MEXICO"
If you want to use the wildcard you must use 'like' instead of '='

inner query of subqery returning multiple rows

I am not that experience in sql so please forgive if its not a good question to ask,but i researched around almost for 3-4 days but no able to solve.
My problem is i have a table which have multiple image names in it,so what i have to do is whoever is the follower of a particular user i have to get the imaged from this table,so one user there can be multiple followers,so i have to fetch the images posted by all the followers.
Here is the subquery code snippet i am using.
SELECT id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email=ANY(SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com')
So the inner query here returns multiple values,for each value(being_followed) i have to fetch all the images and display it,but with this query each time i get only one image.I tried IN also but didnot work out.
Table structure:-
Outfitpic_list table
id|outfit_image|datetime|Email|image_title|description
Follower_table
bring_followed|follower
Please help,I am stuck..!!
Thank you..!!
I think your problem may be the = sign between "E-mail" and "Any". Try this statement:
SELECT
id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email IN
(
SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com'
)
It's the same statement, without the = sign, and the ANY keyword replaced with IN. (I cleaned it up a little to make it more readable)

MySQL: showing totals

I am trying to figure out how to have PHP check and print 2 different functions.
Both of these questions are referring to table called "remix".
The first, and more important problem at the minute, is I would like to know how to show how many DIFFERENT values are under "author", as to compile the amount of total authors registered. I need to know not only how to most efficiently use COUNT on returning UNIQUE names under "author", but how to show it inline with the total number of rows, which are currently numbered.
The second question would be asking how I would be able to set up a top 3 artists, based on how many times their name occurs in a list. This also would show on the same page as the above code.
Here is my current code:
require 'remix/archive/connect.php';
mysql_select_db($remix);
$recentsong = mysql_query("SELECT ID,song,author,filename FROM remix ORDER by ID desc limit 1;");
$row = mysql_fetch_array($recentsong);
echo'
<TABLE BORDER=1><TR><TD WIDTH=500>
Currently '.$row['ID'].' Remixes by **(want total artists here)** artists.<BR>
Most recent song: <A HREF=remix/archive/'.$row['filename'].'>'.$row['song'].'</A> by <FONT COLOR=white>'.$row['author'].'</FONT>
So as you can see, I have it currently set up to show the most recent song (not the most efficient way), but want the other things in there, such as at least the top contributor, but don't know if I would be able to put it all in one php block, break it, or be able to do it all within one quarry call, with the right code.
Thanks for any help!
I'm not sure I really understood everything in your question but we'll work this through together :p
I've created an SQLFiddle to work on some test data: http://sqlfiddle.com/#!2/9b613/1/0.
Note the INDEX on the author field, it will assure good performance :)
In order to know how to show how many DIFFERENT values are under "author" you can use:
SELECT COUNT(DISTINCT author) as TOTAL_AUTHORS
FROM remix;
In order to know the total number of rows, which are currently numbered you can use:
SELECT COUNT(*) as TOTAL_SONGS
FROM remix;
And you can combine both in a single query:
SELECT
COUNT(DISTINCT author) as TOTAL_AUTHORS,
COUNT(*) as TOTAL_SONGS
FROM remix;
To the top 3 subject now. This query will give you the 3 authors with the greatest number of songs, first one on top:
SELECT
author,
COUNT(*) as AUTHOR_SONGS
FROM remix
GROUP BY author
ORDER BY AUTHOR_SONGS DESC
LIMIT 3;
Let me know if this answer is incomplete and have fun with SQL !
Edit1: Well, just rewrite your PHP code in:
(...)
$recentsong = mysql_query("SELECT COUNT(DISTINCT author) as TOTAL_AUTHORS, COUNT(*) as TOTAL_SONGS FROM remix;");
$row = mysql_fetch_array($recentsong);
(...)
Currently '.$row['TOTAL_SONGS'].' Remixes by '.$row['TOTAL_AUTHORS'].' artists.<BR>
(...)
For the top3 part, use another mysql_query and create your table on the fly :)