Sql Distinct Count of Duplicates - php

I am doing a query on a mysql database. I have a main table where users are stored and another table where friends of that user are stored. For each user I want to see how many
friends they have. This is what I'm getting.
ID FirstName LastName FriendID
1 Andrew Smith 1
1 Andrew Smith 5
1 Andrew Smith 9
2 John Doe 3
2 John Doe 5
This is what I want to get.
ID FirstName LastName Friends
1 Andrew Smith 3
2 John Doe 2
If this is not enough detail to go on let me know and I will also show the tables and query I used.

SELECT ID, FirstName, LastName, COUNT(FriendID) AS Friends
FROM Users GROUP BY ID, FirstName, LastName
One hopes you're not really storing FirstName and LastName in every UserFriendLink record. If you are, it's time to normalize your database with a Users table (with ID, First, and Last) and a UserFriendsLink table (with UserID and FriendID).

Related

order by specific word count in mysql

I need to order the results based on the repeatness of the word using mysql.
Here is my sample table
id Name keywords Description
1 John John, USA John is good boy. John, John
2 Alex Alex, John Alex is a friend of john.
3 Rocky John Rocky
4 John John,John John, John, John, John, John
Will take an "John" as example. In first row "John" is repeated 5 times, 2 times repeated in second row, 1 time repeated in 3rd row and 8 times repeated in 4th row. I need to show the results based on the count descending.
Select * From table Where name like '%John%' OR keywords like '%John%' OR Description like '%John%'
So it will show in below order
id Name keywords Description
4 John John,John John, John, John, John, John
1 John John, USA John is good boy. John, John
2 Alex Alex, John Alex is a friend of john.
3 Rocky John Rocky
This will do the trick:
SELECT id,Name,keywords,Description,
ROUND (
(
LENGTH(CONCAT(Name,keywords,Description))
-LENGTH(REPLACE( CONCAT(Name,keywords,Description), "John", "") )
) / LENGTH("John")
) AS count
FROM tbl ORDER BY `count` desc
see here: Demo
Update
If you want to look for multiple (different) words per record you
you should use a user-defined function (UDF) like
CREATE function wcnt(wrd varchar(32), str varchar(1000)) returns int
RETURN ROUND ((LENGTH(CONCAT(str))-LENGTH(REPLACE( CONCAT(str),wrd,"")))/LENGTH(wrd));
see here: function-demo
or here for a combination of the first query with the UDF
SELECT * FROM T
ORDER BY FIND_IN_SET('John',Description) DESC
FIDDLE

Add a column count in a MySQL query

I am trying to achieve a strange query. I have a table like this:
table People
-----------------------
| id | name | family |
+----+------+--------+
| 1 | Bob | Smith |
+----+------+--------+
| 2 | Joe | Smith |
----------------------
I want to return an assoc array like this
id : 1
name : bob
family : smith
familySize : 2
So something like this
"SELECT id, name, family, familySize FROM People"
How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned.
Thank you.
The above 2 answers won't work with multiple families.
You can do something like this:
SELECT id, name, family, familySize FROM People p1
JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2
USING(family)
You can do it like this
SELECT id, name, family, count(id) as familySize FROM People
"SELECT id, name, family, count(family) as familySize FROM People group by
family"
I would like to mention here that what if two or three families have the same surname "Smith". It won't give you the desired results.
What I suggest you is while inserting the data in the table assign a family head and all the family members have a field called family_ID has primary key as value of family_head.
This will give you accurate results with 1000's of people. I have made a family portal has over 12k members now and it works fine for me.
Hope it helps.

Inserting information with checkboxes

Here's the problem:
The user will input his information on the required fields. Then the user will choose a selection in check boxes (the user can choose multiple) which will be saved in database (the value of the check box).
For example:
David selected 2 choices. Sports for example. David choose Basketball and Volleyball.
In my database, it would look like this:
| id | firstname | lastname | sports |
| 1 | David | White | Basketball |
| 2 | David | White | Volleyball |
My main problem is if I have to alter or delete the information, only one row will be altered or deleted which is a big problem. I can't make it like in explode or implode cause I have display the count of how many user have chosen a certain sport.
How am I able to solve this problem?
Looks like you need to normalize your table. You can create a table to store the person data:
person = (personid, firstname, lastname, other fields related to person)
and a table to store the choices:
sport = (sportid, name, other data related to sport)
And finally a table to manage the relationship:
PersonSport = (personid, sportid)
Then in the above scenario your data will be:
Person
personid Firstname Lastname
1 David White
2 Sam Black
and
Sport
sportid name
1 Basketball
2 Football
3 Tiddlywinks
and
PersonSport
Personid Sportid
1 1
1 2
2 3
2 1
To count how many users selected a sport:
Select count(*) from PersonSport where sportid = 1;

PHP MySQL combine cells from different row with same value

I have a database that has id numbers, names, class period, and teacher name. Each row includes a student's id, name, period, and teacher which means that there are multiple rows for each student. That's not my problem. My problem is that some classes have two teachers listed...which means there are two separate rows for 1 class period, one for each teacher. Unfortunately I have no control over the formatting of the data since it's exported from a system that doesn't have a lot of formatting options.
Here is an example, notice how rows 23 and 24 are for the same class period and student, but the only thing different is the teacher names.
pk id last first period teacher
14 12345 Smith John 3 HARRIS
15 12345 Smith John 8 LEAL
17 12345 Smith John 1 HOUSTON
23 56789 Doe Jane 8 MERCER
24 56789 Doe Jane 8 RUIZ
25 56789 Doe Jane 3 BECK
26 56789 Doe Jane 1 STEED
I would like to combine the two rows with the same period number and student name into one row. All the information would remain the same except the two different teacher's names would be combined into something like "Mercer & Ruiz." Ideally the final result would look something like,
24 56789 Doe Jane 8 MERCER & RUIZ
Is this possible using PHP and/or MySQL? I'm not looking for anyone to write the entire code or anything. I just can't seem to think of a way to accomplish it. I'd be happy with any direction/indication of a way to go about this.
As always, thanks for your time and help.
SELECT MAX(pk),
ID,
`last`,
`first`,
GROUP_CONCAT(teacher SEPARATOR ' & ') teachers
FROM tableName
// WHERE clause here...
GROUP BY `last`, `first`, `Period`
// ORDER BY clause here....
SQLFiddle Demo
SOOURCE
GROUP_CONCAT()
SELECT pk,id,last,first,period GROUP_CONCAT(teacher)
FROM table
GROUP BY id, first,last,period
Should do what you need.

MySQL Relational friends scheme?

I was wondering how you'd work a PHP and MySQL Friends system?
I was thinking like, in the users table there would be a colum titled friends which would hold data with other user IDs who they are friends with seperated by commas,
for example, 1,3,56,3 - then explode this and foreach the array?Would that work?
That is one way to do it.
You may want to consider creating a new row for each friend.
For example:
Friend ID: 1
Friend Name: Bob
Friend ID: 2
Friend Name: Ron
Friend ID: 3
Friend Name: Joe
If Bob was friends with both Ron and Joe there would be 2 records in the friends table
id user friend
1 1 2
2 1 3
Then if joe became friends with bob but not ron the table would end up being
id user friend
1 1 2
2 1 3
3 3 1
This gives you flexibility down the road to add in more complex queries.
Don't do it as comma-separated strings, have a user_friends table with each friend relationship as a record. A comma-separated string isn't going to be usefully indexable or queryable.
Important example:
Friend 1 is connected with Friend 2
You have to lookup the user_id AND the friend_id to find all the friends of Friend 1

Categories