Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Count How Many Matching Rows Exsist


I am new to SQL Querries, can someone help me figure out how to get a result?

I have a column in my db called; emails

some of the email addresses in this column may contain similar domains:

person1@site.com
person2@site.com
person3@someothersite.net

I need the result to count and end up being 2 not 3

Not sure how to make the sql statement:
COUNT (*) FROM database_tabe WHERE email='$email' LIKE '%@%.%'

Not sure how to get this result...




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Get Count Of Matching Records
I have two tables, that I am trying to match up rows and count the number of times first_name AND last_name in table A match first_name AND last_name in table B. What is the best way to do this without creating a mess of queries and code?

Matching Multiple Rows
I've got the following tables with the following columns:

property: id, address, number_of_bedrooms
attribute: id, title (e.g. washing machine, central heating, furnished)
property_attribute: property, attribute (composite primary key on both id columns)

what i'm trying to do is select property ids that have all the attributes i'm looking for, for example, all those properties that have a washing machine and are furnished.

I've been trying things like the following which aren't working, probably because the attribute column won't be equal to two different values at once.

SELECT pa.property FROM property_attribute AS pa INNER JOIN attribute AS a ON pa.attribute=a.id WHERE a.title='washing machine' AND a.title='furnished'

this is returning an empty set because, i think, a.title can't have two values at once. what i want to say in pseudo-sql is:

SELECT pa.property FROM property_attribute AS pa INNER JOIN attribute AS a ON pa.attribute=a.id WHERE
(pa.property=X AND a.title='washing machine') AND (pa.property=X AND a.title='furnished')

so the only results that will be returned are where a property has both attributes.

i can't think of how to do this since there will be varying numbers of attributes i need to search on. perhaps i need to use a variable for pa.property - i tried that, setting it to SELECT DISTINCT property FROM property_attribute, but mysql didn't like it because this query returned multiple rows. i may need some kind of set variable or an array.

Problems Retreiving Non Matching Rows
I have been tearing my hair out all day trying to solve this (and I didn't have much to begin with!)

I have two table one containing company details and the other containing contacts for those companies.

T1
ID, CompanyName

T2
ID, CompanyID, ContactName, MainCompanyContact

The MainCompanyContact field is either 1 if the contact is a main contact, or 0 if the contact is a regular contact.

I am trying to come up with a query that will give me a list of every company that has at least one contact but does not have a main contact.

I have tried:

SELECT t1.ID, CompanyName FROM t1, t2
WHERE CompanyID=t1.ID AND MainCompanyContact<>&#391;'

But this returns every company that has a non main contact regardless of it has a main contact or not.

Matching A Row To Multiple Rows In Another Table
I need to match a record in table1 with multiple records in table2,
and return the record only if it matches all those select records on
table2.

I may need MAGIC UNIONS, MAGIC JOINS, or may be simple subqueries. I
am not sure.

Show Rows With No Matching Fields
here is my query which probably needs some more advanced join statements:

select * from orders o, customers c, orders_styles os, styles s where o.customers_id = c.customers_id and os.orders_id = o.orders_id and os.styles_id = s.styles_id group by o.orders_id

the problem is that sometimes, because of user input, there will be no matching fields in the tables orders_styles or styles (no rows with matching orders_id exists in table orders_styles to table orders). I still want to show these rows however. Right now, as you can see it only displays rows that have matching rows in orders_styles and styles.

SELECT Conditional... Matching NULL Rows
I am trying to use a SELECT query to retrieve records from a table that have a certain row set to NULL. However when I try a query like the one below... it is not returning any records, eventhough there are thousands of records that have NULL in the 'row1' row.

Example query:

PHP

$query = "SELECT * FROM table WHERE row1=NULL ORDER BY date DESC";

Enable The Option Flag Return Matching Rows
I would like to know if it's possible to enable the "Return matching rows" flag with a connection string. With a dsn connection i already know how can i do this.

Get A Count And Some Rows
Can I get a count on the total rows but not return all of them, let's say just get the 10 first rows.

Count Rows
with php and mysql:
How we can count rows in a table?

Count The Rows
I've built quite a few large join statements, which cross-reference 6 or 7 tables each. I'm using LIMIT to allow for pagination, which works fine.
However, I need to find out how many rows were returned in total, and don't fancy throwing in another join to count() the results with some where statements.
Anyway I can quickly find out what would've been returned without the LIMIT?

Count Multiple Rows
I have a table that tracks dealer transactions. The fields are Date, Dealership, Amount, A, D, W, F. A=Approved D=Denied, W=Withdrawn and F=Funded. I have made it where if a loan has been approved then A would =1 and D W F would be null. Same goes if the record was withdrawn W would =1 and the other would be null.

So here is my problem:

I want to group by dealership and then count how many were approved, denied, withdrawn, and funded. i am running version 3.23.58. After doing much research I either need to do unions or subqueries. However, both are not availble until 4.x. Is it possible to do what I am looking to do without upgrading?

Count() Rows With 0 Matches
I am using the code below to select all the 'centres' in the database that have 'sessions' today.

SELECT c.*, r.region, COUNT(*) AS count
FROM centres c, regions r, sessions st
WHERE c.c_id=st.c_id
AND st.session_date=CURDATE()
AND c.region_id=r.region_id
This works and the results might look like:

centre / count
centre1 / 20
centre2 / 10
centre3 / 3

However, is there a way to get MySQL to also select centres from the database that have no matches in the sessions table? So the results will look like this:

centre / count
centre1 / 20
centre2 / 10
centre3 / 3
centre4 / 0
centre5 / 0
centre6 / 0

Count Same Field In Rows
i need to calculate the number of the same IP address that appear in the database, how can i do that?
example of the database:
IP Address Date and Time
127.0.0.1 5/23/2007
127.0.0.1 5/24/2007
192.168.1.2 5/25/2007
192.168.1.5 5/26/2007
127.0.0.1 5/27/2007

Count Identical Rows
I've got a log table looking like this:Code:

user | action | time
| |
a | click | 2005-05-05
a | login | 2005-04-05
b | logout | 2005-03-02
b | click | 2005-01-25

And now I wanna display the statistics in a neat interface. But I'm having problems... is there a way to select from the above table and get rows like this:Code:
user | click | login | logout
| | |
a | 56 | 23 | 45
b | 45 | 2 | 0
c | 12 | 32 | 32

Perhaps this is more than I could expect from MySQL?

How To Get Count Of Rows Returned While Using Group & Having?
i'm using the having keyword to find certain set of rows and they are working properly.

but what i want is , i want to count the total number of rows returned by this query using mysql.

select name,count(date) from emp group by date having count(date)>3;
this returned returns all the names that have more that 3 entries in the same date. it returned 5 rows and how can i get the count of rows(5) the query returned .

Retrieve Everything AND Count Rows In One Query
set rsminmax = con.execute("SELECT * FROM `minirules_minmax` where RuleId = '" & contractId & "'")
set rsminmax2 = con.execute("SELECT COUNT(*) FROM `minirules_minmax` where RuleId = '" & contractId & "'")


Is there any way to do this in one SQL query?

Count Fields Over Multiple Rows
I have a database like this

id, field1,field2,field3,field4,field5

Database contains 100 rows, some rows have no fields filled, some
1field , some 2 fields etc.

How would i count the number of fields filled in total?

So the outcome is (number of fields filled in row1)+(number of fields
filled in row2)+(number of fields filled in
row3)....................+(number of fields filled in row100)

Slow Count(*) On Many Indexed Rows
we have a 10 million rows table. One field 'stamped' is either 'yes' or 'no'.
About half the rows are 'yes' and half are 'no'.
Table is indexed on 'stamped'.
We just need the count on 'yes'.

SELECT count(*) from T where stamped='yes'

or <>'no' or >'n'... is very slow.

Is there a better approach / query to get a fast result?

Count Number Of Rows Returned?
this is my connect and everything code:

<?php // connect to the mysql database server.
mysql_connect ($dbhost, $dbusername, $dbuserpass);
mysql_select_db($dbname) or die(mysql_error());
$query = "SELECT DISTINCT category FROM $tuttable";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo ($row['category']." | ");
}
echo count($row);
?>

Notice "echo count($row);" How do i get this to work properly. It only returns one, because there is only 1 that it is working on. I want to return the count of all the rows that fit that query.

Select Count(*) Showing -1 Rows.
In one of my preliminary tests with mysql, the below statement is showing the following way. What does -1 rows signify in the table with the select count(*) query. Is this (-1 rows in the query result) an error condition to be taken care ?.

bash-2.03# ./mysql -u test
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 8 to server version: 5.0.18-max

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql> use test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A Code:

Trying To Count The Number Of Rows In A Result Set After Query
The user fills out this form to sign up to the website, the form checks the database to see if the username has already been taken with the code:

$conn = mysql_connect("localhost:3306", "root", "********")
                                    or die ("Error With Connection");
        echo("connected<br><br>");
        $db_sel = mysql_select_db("game",$conn)
                                    or die ("Error With Database");
        $check = "select * from users where 'username' = '$username'";
        $db_sel = mysql_query($check,$conn)
                or die (mysql_error());

Count Or Select Only The Populated Rows In A Column?
I'm trying to COUNT the number of populated rows within a column named, 'column_03', but first instead of using COUNT i'm using SELECT to see where the numbers are coming from.
lets say i use the following code...

SELECT column_03
FROM table_name
WHERE table_name.column_01 = 'IN''
AND table.name.column_02 ='GENER"

the result is a total number of 10 records. i can see that 'column_03' has 6 rows that are populated and 4 rows are empty. now what i want to do is select only the 6 rows that are popluated, once i now how to do that i can then use COUNT. Any suggestions?

Limiting Rows Returned Based On Count
say if I have 3000 records in my db, and I want to get rows 200~300 when orderd by a specific field in this table, is there a easy way to do it?

I have something like:

select * from table_name order by ID desc limit ....

but I am not sure if this syntax allows me to do what I am trying to do .

Return A Count Of Number Of Rows Before Desired Row.
Anyone know how? find_in_set doesn't seem to be able to do what I want since I am not searching through an array but am actually running a query.

What I really want is to be able to select all until something = something. I've searched the realm of google but cannot come up with anything useful, and so I am wondering if maybe I don't know the right words to be looking for.

Problem With Left Join And Count, Returning More Rows Than What It Should
Am having a problem with a query, strangely ...

PHP

SELECT *
FROM table1 AS mt
LEFT JOIN table2 AS pt ON mt.p_id = pt.p_id
WHERE my_field = 'somevalue'

Is returning a much bigger number (12 rows) for me, then what it should.

PHP

SELECT *
FROM table2
WHERE my_field = 'somevalue'

Is returning only 2 rows

Count One Table's Rows From Multi Table Query
here are my tables (condensed)

FEEDS
feed_id
site_id

SITE
site_id
site_name

ARTICLES
article_id
feed_id
link

I want to create a query that returns the total number of articles for every site_id (which is unique in the SITE table). I have this:

PHP

$gsite = mysql_query("SELECT site.site_id, feeds.feed_id, COUNT(articles.article_id) AS acont FROM site,feeds,articles
WHERE feeds.site_id = site.site_id AND articles.feed_id = feeds.feed_id group by site.site_id", $connection)
or die(mysql_error());

The query does not use JOIN, ON and all that good stuff.

I just need the following variables to run through a loop:

site_id
the number of articles rows per site_id

Agregate Count Return All Rows, Left Join
I have 2 tables on a lyric discussion site

Titles
   title_id            
   title_name                   
   title_lyricist                   
   title_lyrics                   
   title_artist                   
   title_entered  

And POSTS
   post_id               
   title_id                 
   post_author                   
   post_text  

I want to be able to list all the titles, and count the # of posts for each title. The problem is some titles have zero posts so my query ignores thos titles, butI syill want them returnd where Ill add a ')' for count.

This is the best i could come up with, but still only those that have posts are returned. I still want the titles that don't have a match in the posts table to be returned with a total_count of zero.

Trying To Pull Id, Count And Title But Lose Rows When I Add Extra Join
i'm trying to extract some information from my database, the query being

PHP

SELECT grps_c.catid, grps_c.title, COUNT(grps.groupid) AS COUNT
            FROM grps
            RIGHT JOIN grps_category grps_c ON (grps_c.catid = grps.catid)
            GROUP BY grps_c.catid
            ORDER BY grps_c.title

which works fine. however some of the groups (grps.groupid) are hidden and i don't want to count them, so my thinking was add

PHP

LEFT JOIN grps_setting grps_s ON (grps_s.groupid = grps.groupid AND grps_s.hidden_group != &#391;')

however adding that removes the rows that have a 'count' or NULL or Zero.

Matching More Than One Value
I have three tables (there are more in the db):

TABLE p                         
profile_id(pri)
name
---------
TABLE e        
experience_id(pri)  
category_id(fn)    
experience            
----------
TABLE p_e
profile_id(comp)
experience_id(comp)
level
----------

My current query:
"SELECT p_e.profile_id,p.name FROM p_e,e,p WHERE (e.category_id = '1' OR e.category_id = '2') && p_e.experience_id = e.experience_id && p_e.profile_id = p.profile_id && p_e.level != 'None' GROUP BY p_e.profile_id"

I would like to select all records from PROFILE_EXPERIENCE that belong to certain categories. If I use (category_id = '1' OR category_id = '2') this will not return records that contain both 1 and 2. I cannot use (category_id = '1' AND category_id = '2') for obvious reasons.

String Matching
If i have the following table:

--------------
| ID | Color |
--------------
| 1 | Blue |
| 2 | Red |
--------------

If I have a HTML form and the user inputs in a textfield "The sky is usually blue in color".

Bitwise Matching
I am using an unsigned INT to store a list of categories for a particular product. Some products can be listed in multiple categories. For example, categories might be 1-Stationery, 2-Furniture, 3-Hardware, etc.

When an item is in multiple categories, i just set the appropriate bit, for example an item that might be listed in stationery and hardware would have bits 1 and 3 set to 1, givng the category a value of 5.

A search then uses a bitwise & to return values based on a user search, for example if a user searches for "stationary and hardware"

Item 1 = 101 (binary)
Search = 101 (binary)
Result = 101 (item1 binary).

What I would like to know is if it's possible to order the results in order of the number of matching bits?

For example 2 items, first with bits 101 set, second with bits 100 set, I would like to return both items, but obviously rank the one with most bits matching the search higher. Is this possible?

Pattern Matching?
I have some data I want to pull out of one field and put into another. The tricky part is that the field the data is in is a text field, and the data could be anywhere in there. So I need to do some sort of pattern matching to find it.

Here is an example of the query I want to run, but I don't know what to put for the question mark.

UPDATE Building SET architect = ? WHERE description LIKE '%Architect: %';

In the description field, architects are in this format:

Architect: name of architect
or
Architect: name of architect, http://example.com/

The name of the architect may contain commas.

So the pattern match needs to do this:

Find "Architect: "
then find ", http://" or "
" or end of field after that
take the text in between and put it in the architect field.

Pattern Matching
I am trying to match 2 tables based on a pattern match (right to left) of cdr.dst and rates.destination. I can get this query to give me the results i want, but it matches all instances instead of the most relevant only? Here are my 2 tables: Code:

Matching Two Tables
I am trying to pull information from two different tables to be displayed in a php file. Both of these tables share the same field of product_id. I need to pull the product name from one table and the location of the image from another table and display them. This is for a store system and I'm randomly trying to show three products on my homepage.

I am just unsure as to how to pull the information. I have code that connects to the DB already and randomly grabs a product name. My next step I am guess is to match the product_id of the name pulled to the other table and get the filename of the image stored in the other table. This is the code I already have.

<?php

$link = mysql_connect("localhost", "tristate_store", "pword") or die (mysql_error ());

mysql_select_db ('tristate_store', $link) or die (mysql_error ());

$desc = mysql_query ("SELECT * FROM `storeproducts_description` ORDER BY RAND() LIMIT 0,1") or die (mysql_error ());

$res = mysql_fetch_assoc ($desc);

echo ''. $res['products_name'] . ' Click here ' . $res['products_id'];

?>

Pattern Matching
I have a question, what is faster in pattern matching using LIKE or REGXP?
What is the advantages of using LIKE and also the advantages of using REGXP?

Pattern Matching
Am switching from MS Access to mysql, which I'm told is better. I have a table, location, of place names eg:

place
-----
London
Hong Kong
New York

and wish to search for any places in a user-entered search string eg "London Hong Kong"

In Access the query
  SELECT * FROM location
  WHERE 'London Hong Kong' LIKE '*'&place&'*'
returns both Hong Kong and London

But in MySQL nothing is returned, even replacing the MS-specific * with %

How is this achieved in MySQL?

Pattern Matching
I have a table, location, of place names eg

place
-----
London
Hong Kong
New York

and wish to search for any places in a user-entered search string eg
"London Hong Kong"

In Access the query
SELECT * FROM location
WHERE 'London Hong Kong' LIKE '*'&place&'*'
returns both Hong Kong and London

But in MySQL nothing is returned, even replacing the MS-specific *
with %

How is this achieved in MySQL?

Pattern Matching
I am having problems trying to do a pattern match between two tables.
I have a table with and id column and a title of a book. In the second I have the title and the author. I want to take the title from second table and retreive the id from the first matching the titles?

Matching Id Numbers
I have a problem with a user management system.
Simply i have 3 tables.

Table 1 - ID1, Name, Pass

Table 2 - ID2, Name, ItemID

Table 3 - ID3, ItemID, ItemName

Let user login using info from table 1, once logged in query table 2 to get all the ItemID's for the logged in user.Once this is done I need to finally query table 3 looking for matches to the itemid's from table 2 in order to show how many orders for each item but only when the itemid is associated with the user from tables 1 and 2.

Matching Profiles
I am working on a dating website and have to match profiles that are stored in multiple tables. What I am trying to do is to sort results in a descending order starting from best match to the worst, so what I thought of is to use the Levenshtein or similar_text functions on the different values stored in the profile, but later I realized that such an idea would be very time consuming when dealing with thousands records.
Here is an example that shows the structure of my tables:

member[id, login]
look[id_mmeber, weight, hair_color, eyes_color, have_galsses]
pref[id_member, smoke, drink, like_clubbing, like_cafes]
In reality , the profile have more than 3 tables, but 3 will be enough to explain it
So the big question is, is there a way to acheive this by using SQL only ?

#1136 - Column Count Doesn't Match Value Count At Row 1
I'm getting the above error with the following SQL Statement. I cannot seem to find the error in the code. The select statement does pull multiple rows.

I'm using my SQL version: 4.1.19

Any clue on why this isn't working?

INSERT INTO `Grants` ( `Project_Code` , `Grant_Code` , `Fiscal_Year` , `Capital` )
VALUES (
(
SELECT Project_Code, Grant_Code, FY, SUM( Capital )
FROM Grants_Temp
WHERE Project_Code = 'OSUT'
AND FY = '2006'
AND Claim_Month = '072006'
GROUP BY Grant_Code
ORDER BY Grant_Code
)
)

Matching SQL And Database Query
If I open up phpMyAdmin, click on a database named Gypsy, then click on the SQL tab and paste in the following:

GRANT ALL PRIVILEGES ON Gypsy.* TO 'James_Bond'@'localhost' IDENTIFIED BY î‘'

FLUSH PRIVILEGES;
I know it's at least partially working because I see James_Bond listed among the users when I click on "Privileges" - and I don't see James_Bond listed for any other database.

But when I try the following database connection...

PHP

$link = mysql_connect ("localhost" , "James_Bond", "007") or die(mysql_error());
mysql_select_db ("Gypsy", $link) or die(mysql_error());

I get this error message:

Quote:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'James_Bond'@'localhost' (using password: YES) in /Users/MyName/Sites/Geobop/index.php on line 194
Access denied for user 'James_Bond'@'localhost' (using password: YES)

Character Matching Question
Is there any special character to be used if in the following query, i don't care about the user's gender, (that is, i want to have as result both men and women)???

I'm trying:

$query="SELECT * FROM users WHERE gender LIKE '%' ";

or

$query="SELECT * FROM cast WHERE gender LIKE '.' ";

or

$query="SELECT * FROM cast WHERE gender LIKE '*' ";

but none seems to work.

Matching Escaped Strings
ID|Name
================
1|Author's

As you can see, the name value has been escaped. Now, the question is,
how do you match on a value that has escaped charaters? I've tried the
following

SELECT * FROM table WHERE Name = 'Author's'

SELECT * FROM table WHERE Name LIKE 'Author's'
SELECT * FROM table WHERE Name = '%Author's%'
SELECT * FROM table WHERE Name = 'Author''s'
SELECT * FROM table WHERE Name = "Author's"
SELECT * FROM table WHERE Name = "Author's"

And none of them work.

MySQL Text Matching
I have a table of ~5,000,000 records (ID, name, title) and a second table of ~2,000,000 records (ID, name, title).

What i need to do is return the ID's from the first table where there is no exact match with a name/title in the second table.  So if a row in table 1 is (3, Tom, Arnold) and there is a row in table 2 (5, Tom, Arnold)...  I would NOT return 3.
Conversly, if there is no row in table 2 with name=Tom, title=Arnold then I WOULD return 3.

But, when i say exact match I mean a match that ignores case and removes trailing white space.  So " ToM" = "tom"

I know how to do this matching but the way in which I would do it would take FOREVER to run...  I was wondering if anyone has any idea on how to write a lightning fast query to complete this objective :)

The String columns (name, title) are Varchars so I think this means i cannot use the Match keyword?

Pattern Matching With REPLACE()
I am trying to sort results using a selective case-insensitive REPLACE() of "the " only at the beginning of the string like this:

SELECT * ,
REPLACE( title, '^the ', '' ) AS sortName
FROM testing
ORDER BY sortName;

Which produces:

+----+----------+----------+
| id | title | sortName |
+----+----------+----------+
| 3 | Ants | Ants |
| 1 | flag | flag |
| 4 | the aunt | the aunt |
| 2 | The fog | The fog |
+----+----------+----------+

Now I can do this:

SELECT * ,
REPLACE( title, 'the ', '' ) AS sortName
FROM testing
ORDER BY sortName;

Which is a little better:
+----+----------+----------+
| id | title | sortName |
+----+----------+----------+
| 3 | Ants | Ants |
| 4 | the aunt | aunt |
| 1 | flag | flag |
| 2 | The fog | The fog |
+----+----------+----------+

Is there some way to use regex terms with REPLACE() ?

Limit On Matching Results Only?
Is there a way to do a limit with a starting and ending value that works like a:

LIMIT 10, 20

only it pulls the 10 resulting rows that matched the where clause of the query vs. just showing the 10 rows regardless of the where clause?

Example:

select product_name from products where product_count > 0 limit $start, $end;

The desired result is that the query returns however many rows fall between the value of $start and $end, lets say 10 rows, but the 10 rows returned are the first 10 rows that matched the where clause of the query and not just the next 10 rows of the table.

Matching Escaped Strings
I have the following info in my database

ID|Name
================
1|Author's

As you can see, the name value has been escaped. Now, the question is,
how do you match on a value that has escaped charaters? I've tried the
following

SELECT * FROM table WHERE Name = 'Author's'

SELECT * FROM table WHERE Name LIKE 'Author's'
SELECT * FROM table WHERE Name = '%Author's%'
SELECT * FROM table WHERE Name = 'Author''s'
SELECT * FROM table WHERE Name = "Author's"
SELECT * FROM table WHERE Name = "Author's"

And none of them work.

Matching Password With One Already In Database
I am using PHP5 I have written the code to insert a password into the data base for a registrtion form.When I am trying to to match using a log in form so I can continue to the next page I keep getting the error message Username and password are not the same as those on file. Here is my code for inseting into database:

//Make the Query
$query = "INSERT INTO registration (first_name, last_name, email, user_name, password)
VALUES('$fn', '$ln', '$e', '$un', PASSWORD('$p'))";
$result = @mysql_query($query); // Run the query.

Here is my code for retrieving it

$query = "SELECT user_id, first_name FROM registration WHERE user_name1 ='$un' AND password1=PASSWORD('$p')";
$result = @mysql_query ($query);
$row = mysql_fetch_array ($result, MYSQL_NUM);

Can anyone tell me what I am doing wrong.


Copyright © 2005-08 www.BigResource.com, All rights reserved