Till now I still cannot differentiate between WHERE clause and WHERE IN clause. For example, I have:
Query = mysqli($mysql_connect, "SELECT * From Customer Where CustomerID IN ('CU001', 'CU002', 'CU003')");
Is this same as Query = mysql($mysql_connect, "SELECT * FROM Customer Where CustomerID = 'CU001' AND CustomerID= 'CU002' AND CustomerID='CU003')";?
If it the same, which one is the best practice to follow? Thanks.
The WHERE clause can be combined with AND, OR and NOT operators. The AND and OR operators are used to filter records based on more than one condition. The AND operator displays a record if all the conditions separated by AND is TRUE but should not be used for single column as you have used in 2nd query (it will not find any record).
The In operator finds all records which falls within specified values, like OR condition.
Related
I wanted to compare two strings in MySQL irrespective of the order of two strings:
Here is an example, Say i have a string as 'A1,B1,C1' and i wanted to find out how many rows are there in table where the column value contains the same string. This can be done easily with like query as given below:
select count(1) as attr_count from attribute_lists where attr_tab like :value_names;
I will execute this query from PHP using PDO and the string 'A1,B1,C1' will be binded to value_names. However what i also want is if any row contains the same set values but in different order then also they should be considered in count. Say if there is a row with column value as 'B1,A1,C1' then that should be matched and counted as 1.
Irrespective of the order in which the strings are they should be matched. Any help on how can i write such a query?
select count(1) as attr_count from attribute_lists where attr_tab like '%'+value_name'%'
I'm currently learning how to build a site in PHP MySQL. However, I seem to fail to understand COUNT() as count and wouldn't mind some further explanation.
I get the principles of COUNT, 0 || 1, and how it returns all the values that pertain to that query.
But, don't see how COUNT as count works. Anyhow, this is how the code I'm writing goes - so we have a working example - and where I first became perplexed.
"SELECT COUNT(id) as count, id
FROM user
WHERE email='$email' AND password='".md5$password."'"
That is what is called alias which is sometimes used to show a more appealing column header to users or the calling code
SELECT COUNT(`id`) as `count`....
will print
count
--------
5
The alias standing as the column header instead of any arbitrary string: See the SQLFiddle to see the difference
From the fiddle you can see that the header column looks somehow e.g.
count(*)
--------
5
With Count() you can count the returning rows of a result set. The also the official MySQL documentation about count:
Databases are often used to answer the question, “How often does a certain type of data occur in a table?” For example, you might want to know how many pets you have, or how many pets each owner has, or you might want to perform various kinds of census operations on your animals.
Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet. COUNT(*) counts the number of rows, so the query to count your animals looks like this:
SELECT COUNT(*) FROM pet;
The part with AS count means that this colum will get a name which you can use e.g. in PHP. See also this explenation on w3schools:
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.
An alias name could be anything, but usually it is short.
as count is just an alias. You can use as for any field or method selected. it means you change the name of the column being returned in your dataset.
SELECT `field` as another_name
So:
SELECT COUNT(*) as `count`
Just renames the column from COUNT(*) to count making it easier to work with whereever you are maniuplating your result set.
It also makes for easier access within your current query. Many would do the following with large table names:
SELECT * FROM `table_with_ridiculous_name` as twrn WHERE twrn.id = 1
If you ran this sql:
SELECT COUNT(id), id ....
You would get (after doing a *_fetch_assoc) $row['numberofrecordshere'] which would be very hard to echo (or use in a comparison) unless you knew how many records there would be (which would defeat the purpose of this result, anyway)
Returning it as count allows you to get to it in the resulting array by using $row['count']
$num = "1";
$result = mysql_query("SELECT * FROM perp_users WHERE concat(activate) LIKE '$num'");
just need a simple explanation
I know its retrieving a result from sql selecting from a table then i get confused afterwards.
Please explain thanks!
This snippet is pulling all columns from the perp_users table, where the column activate is similar to '1';
It can probably be rewritten as:
SELECT *
FROM perp_users
WHERE activate = '$num';
CONCAT() joins columns together into one result, but since you're only using it on one column, it's unnecessary.
In this usage, concat(activate) is the same as activate. The concat() function concatenates strings, and it would normally be used with multiple arguments, like
... concat (str1, str2, str3, str4, str5) ...
The LIKE operator does a string comparison which is more relaxed than a straight =; it also allows simple wildcards.
The LIKE operator is used to search for a specified pattern in a column. It's most commonly used in conjunction with wildcards.
concat is concatenation, or joining the results from two columns. In this case, it's not doing anything since it's sent only one column. Usually it's sent multiple arguments to contactenate together, ie. concat (col1, col2, col3).
The full query is selecting all columns from the table perp_users where activate matches the pattern $num. In this case, both concat() and LIKE are unnecessary.
I have the following SQL statement:
mysql_query("SELECT * FROM `friends` WHERE friend1='$username' OR friend2='$username' AND confirmed='1'");
What I'm trying to accomplish is delete from the table select data from the table friends where one of the two fields is equal to your username, and the confirmed field has to equal 1. This doesn't seem to be working though. What's the best way to rewrite it?
Try this with your friend clauses in parenthesis:
SELECT * FROM friends
WHERE (friend1='$username' OR friend2='$username')
AND confirmed='1'
This will ensure that one of your friend conditions is met. No matter which one matches, it'll also check the confirmed bit. If neither friend condition matches, the row isn't part of the resultset.
Maybe your where clause is not evaluating the conditions in the way you expect?
Try:
mysql_query("SELECT * FROM `friends` WHERE (friend1='$username' OR friend2='$username') AND confirmed='1'");
The following link shows operator precedence in mysql, as you can see AND is evaluated before OR , hence your problem.
http://dev.mysql.com/doc/refman/4.1/en/operator-precedence.html
I need to do a few things here and I'm confused on how this should work.
Here are the variables I need to work with:
Date Range
Employee ID
Team
and a possible additional search term (acct_number='$_REQUEST[q]') if someone wants to search for a specific account number.
Each variable is populated with a drop down select, the first option being * for all records. The dates are set using a date picker, calendar style, and it's automatically set as date 1=seven days ago and date 2=today.
My query:
SELECT * FROM table
WHERE job_date BETWEEN '$search_date1' AND '$search_date2' AND
employee_id='$searched_employee' AND team='$searched_team' AND
acct_number='$_REQUEST[q]'
ORDER BY employee_id desc
I know the records are there but my search still returns no records. After the date, the AND employee_id='$searched_employee' could be * so it should return all records and the same goes for the team.
Echoing the variables to try make sure something was set gives me this:
No records found for "Employee" for dates between 2011-05-01 and 2011-05-31 and on team "Team".
Can I not request more with AND in the Select statement after I use the BETWEEN?
Thanks in advance!
--Joel
You cannot use '*' wildcard for WHERE clause.
Try using variables for conditions you put in your query, like:
if( is_numeric( $searched_employee ) )
$employee_cond = " AND employee_id=$searched_employee";
else
$employee_cond = "";
and put $employee_cond inside your query instead of AND employee_id='$searched_employee'.
Repeat for every condition you need.
Put parenthesis around the date range condition:
SELECT * FROM table WHERE (job_date BETWEEN '$search_date1' AND '$search_date2') AND employee_id='$searched_employee' AND team='$searched_team' AND acct_number='$_REQUEST[q]' ORDER BY employee_id desc
I don't think its a matter of your BETWEEN statement as it is the amount of criteria you are "AND"ing together. What you are asking for is ALL of the criteria must be true for it to be included in the set...
Ex: Your from/to dates are May 1 to May 31, but the $Searched_Employee you are looking for had no activity within that range, or the employee is not associated with $searched_team, etc with your Acct_Number.
You are explicitly looking for ALL those conditions. You MAY intend to have some "OR" conditions going on... such as
select
Jobs.*,
Employees.LastName,
Employees.FirstName,
Employees.{whatever other columns}
from
Jobs
join Employees on Jobs.EmployeeID = Employees.ID
where
Jobs.job_Date between StartDate and StopDate
AND Jobs.employee_id = SearchedEmployee
AND Jobs.team = SearchedTeam
AND Jobs.Acct_Number = SearchedAccount
The * is only really used such as count() or for fields to be returned from a query, and NOT within where/join conditions (unless its a count() ). So, above has been modified to keep ALL your "AND" clauses, but also show to get specific or all fields from joined table.
The table names querying from are modified as your actual tables were not available. As you can see, I did the Jobs.* to return ALL fields from that table, but explicitly included Employees.{certain individual fields} from that.
Hope this clarification helps you with future querying...