search in database table by multiple column that maybe not set - mysql

i have a database table with any column. and there is 3 form input in UI page, that a user can search a value in table by these inputs. the user can insert value for one of column (inputs), Two of columns or all of them. means its possible that one or two of inputs value be null and user don't use them for his search.
how to create the search query? because the following code have a problem. if user don't insert the value of all of 3 column, this query will take error.
$query="SELECT * FROM insurance WHERE nationalCode=:nationalCode AND insuranceNumber=:insuranceNumber
AND insuranceType=:insuranceType;";
in other words, i need to search in table across 3 columns if value of 3 these columns have define by user else if user have insert value for 2 of columns search will do by these two columns & if user have insert value only for 1 of column search will do by that 1 column.

If the user did not insert a value, say for nationalCode, I assume the you pass NULL (or an empty string?) as :nationalCode and in this case your condition should be:
nationalCode = :nationalCode OR :nationalCode IS NULL
or:
nationalCode = :nationalCode OR :nationalCode = ''
So for all the columns the statement should be:
SELECT *
FROM insurance
WHERE (nationalCode = :nationalCode OR :nationalCode IS NULL)
AND (insuranceNumber = :insuranceNumber OR :insuranceNumber IS NULL)
AND (insuranceType = :insuranceType OR :insuranceType IS NULL);

Dear #forpas i have used your query and don't have succeed. but with tiny change in your offerd Query a have arrived my gold.
i used both of your code :
nationalCode = :nationalCode OR :nationalCode = ''
and
nationalCode = :nationalCode OR :nationalCode IS NULL
indeed i changed your suggested Query as followin:
$query="SELECT * FROM insurance WHERE
(nationalCode=:nationalCode OR :nationalCode IS NULL OR :nationalCode='') AND
(insuranceNum=:insuranceNum OR :insuranceNum IS NULL OR :insuranceNum='') AND
(insuranceType=:insuranceType OR :insuranceType IS NULL OR :insuranceType='');";
so tanks for your help.

Related

Blank input Parameters in a WHERE condition of a SELECT statement

I have a report with 10 input parameters wherein only two are obligatory, the rest are optional. The problem is, as far as I know, if you use an input parameter that is blank in a WHERE condition of a SELECT statement no records will be selected from a table, so how to fix that ?
lets try something simple:
SELECT * FROM contrat WHERE article = 'sumsung' AND price = null
the user entered an article and did not enter a price
so the query will return nothing because price is null even when we have a contract with a sumsung article
If by blank you mean null or an empty string, you must construct for each of the optional parameters a condition like:
column_name = :optional_param OR :optional_param IS NULL
or:
column_name = :optional_param OR :optional_param = ''
So, your WHERE clause should look like:
WHERE <conditions for the non null parameters>
AND (column_name1 = :optional_param1 OR :optional_param1 IS NULL)
AND (column_name2 = :optional_param2 OR :optional_param2 IS NULL)
AND .......

Use ValueA when JOIN returns a row, otherwise ValueB (like a default)

I have four tables for a form-builder in my databse.
fields (fieldID(PK), typeID, fieldName, ...) - This table is a row by row list of all fields to be in the form
fields_types (typeID(PK), htmlType, ...) - This is a table that links fields to html types (and other settings)
fields_meta (FieldMetaID(PK), FieldID, mName, mValue) - Additional settings for fields, but more specific. A textarea field might have a height attribute, but almost no other field would use that.
fields_tyeps_meta (TypeMetaID(PK), typeID, tmName, tmValue) - Defines what extraneous settings a field can have, and also supplies default values if it's not explicitly set)
So my Query currently looks something like this
SELECT *
FROM Fields F
JOIN Field_Types FT
on FT.FieldID = F.FieldID
LEFT
JOIN Field_Meta FM
on FM.FieldID = F.FieldID
I was wondering if there's a way to join Fields_Types_Meta so that when the row's JOIN to Fields_Meta doesn't return a row (no mValue), it returns tmValue
I realize I can use something like (CASE WHEN mValue = "" THEN tmValue ELSE mValue END) AS UseValue, but I might have fields where I want to allow the value to be set to empty.
Edit: I could probably do something with a subquery and COUNT, using a CASE decision based on that. It might not be the healthiest performance-wise, but this query runs and caches itself til server restart, or until it's told to run again (updates to form design)
It looks like you just want ¢oalesce():
coalesce(FM.mValue, FT.tmValue) as UseValue
When FM.mValue is null, coalesce() returns FT.tmValue instead.
If you have null values in FM that you want to preserve in the result set, then use a case expression instead:
case when FM.FieldID IS NULL THEN FT.tmValue ELSE FM.mValue END as UseValue
This phrases as: when the left join did find a match in FM, use mValue from that row (even if it is null), else use FT.tmValue.

How do edit this mySQL query based on value of column without using PHP?

I want to edit my existing mySQL query based on whether the column show_only_on has a value or not.
If it has a value, then the correct query is the below
Select *
FROM alerts_data
WHERE id = 'abc' AND running_status='idle'
AND FIND_IN_SET("https://www.example.com/pricing", show_only_on)
And if it does not have a value, I just leave out the
AND FIND_IN_SET("https://www.example.com/pricing", show_only_on)
or make the FIND_IN_SET return true.
How can I do this using only this query and not any PHP ?
How about running it through an OR/AND statement?:
Select *
FROM alerts_data
WHERE id = 'abc' AND running_status='idle'
AND (
show_only_on IS NULL /* Whatever check you do to ensure it's not set */
OR FIND_IN_SET("https://www.example.com/pricing", show_only_on)
)
If I understand you correctly, you want to return all records where wither show_only_on is NULL or where show_only_on matches the FIND_IN_SET logic?
Sounds like this:
WHERE
id = 'abc' AND
running_status='idle' AND
(
FIND_IN_SET("https://www.example.com/pricing", show_only_on) OR
show_only_on IS NULL
)
Another option, one that I tend to use in parameterised queries:
WHERE id = 'abc'
AND running_status='idle'
AND COALESCE(show_only_on, "https://www.example.com/pricing") = "https://www.example.com/pricing"
Parameterised:
WHERE id = 'abc'
AND running_status = 'idle'
AND COALESCE(show_only_on, :url) = :url
Note this only works where show_only_on is NULL if and only if the value is considered empty/missing.

mysql - detecting identical rows when theres no primary key

I'm dealing with a situation at work where someone set up some tables without a primary key (arghhh). now I'm trying to compare dev data to prod data and the best I can tell is that theres a slight difference in the number of rows.
I figured the best way I could compare data is to do a join on every column, but I'm getting unexpected results.
to test this out I just joined the same table to itself. This table has 1309 rows.. but when I join on every column i get 1014. Thats less rows. If anything i'd expect to get more. What gives?
select *
from `default_tire_classifications` tc1
join `default_tire_classifications` tc2
on tc1.`marketing_tread_name` = tc2.`marketing_tread_name`
AND tc1.`size` = tc2.`size`
AND tc1.product_category = tc2.product_category
AND tc1.application = tc2.application
AND tc1.vehicle_type = tc2.vehicle_type
AND tc1.oem_part = tc2.oem_part
AND tc1.position = tc2.position
AND tc1.size = tc2.size
AND tc1.sect_wdth = tc2.sect_wdth
AND tc1.aspect_ratio = tc2.aspect_ratio
AND tc1.rim_size = tc2.rim_size
AND tc1.speed_rating = tc2.speed_rating
AND tc1.load_index = tc2.load_index
I suspect some of the columns contain NULL values. An equality comparison to a NULL value yields NULL. (SQL tri-valued Boolean logic.)
To do a comparison that yields TRUE when both sides are NULL, you could do something like this
( tc1.col = tc2.col OR ( tc1.col IS NULL AND tc2.col IS NULL ) )
MySQL also provides a non-standard "null-safe" equality comparison operator <=> (spaceship) that does the same thing.
tc1.col <=> tc2.col
returns either TRUE or FALSE, and will return TRUE when the values on both sides are NULL.
So, replacing the = (equality comparison) operator with <=> operator should resolve the problem with comparing NULL values.
(This isn't to say that NULL values is a problem, or is the only problem.)
If your fields contains NULL, you will lost them. Because NULL = NULL is not true.

Azure table storage - where clause on column that may not exist

I am adding a new column to my azure table. For ex., the table is called 'User' and the new column is called 'ComputationDate'. The 'User' table already exists with rows that do not have this new column 'ComputationDate'. I have a query over it as follows,
var usersDue = from user in Table.Query
where user.ComputationDate != <somedate>
select user;
I want this query to return all user rows that do not have ComputationDate set to 'somedate' and also user rows that do not have this new 'ComputationDate' column defined.
But the query doesn't return the latter set of users. It only returns rows that have 'ComputationDate' set and where the value is not equal to 'somedate'.
Is there any way to get the results I desire without having to get all users and filter it on the client?
It looks like you're trying to do a LINQ to SQL query.
This may serve your needs better:
var usersDue = from user in Table.Query
where user.ComputationDate != <somedate>
|| user.ComputationDate == null
select user;