Pull unique data from a database - MySQL - php

I'm looking to query a table that contains messages, organised with a sender and receiver. I would like to create a query to only return each combination of sender and receiver once. I currently have data stored in a database like so:
sender
receiver
1
2
2
1
3
4
4
3
The output I am looking for is as so:
1 | 2
3 | 4
Is this possible? If so, any hints in the right direction would be much appreciated.

One option uses least() and greatest(), and distinct:
select distinct least(sender, receiver) as user1, greatest(sender, receiver) as user2
from mytable

Related

Same id's but only fetch 1 result

I'm about to make a message system. Instead of making 2 tables like conversations and messages, I would just like to have messages. There would then be a lot of rows with the same user id's like this:
id to_id from_id message
1 1 2 text...
2 1 3 text...
3 2 1 text...
4 1 2 text...
5 1 2 text...
6 1 2 text...
The thing is, that I want to get one of each conversation. If id 1 writes to id 2, then thats 1 conversation, but if id 2 writes a reply to id 1, then it would STILL be only 1 conversation.
In the above example, there is only 2 conversations (id 1 to id 3) and (id 1 to id 2 and reverse).
How can i Achieve this. My idea is that there must be something simpler than DISTINCT.
I might go for a related table but to keep it simple, just add the column conv_id.
When a message is created, create a new conv_id and add it to the table row with the other data. When a message is replied to just use that conv_id for the new row.
When you want to retrieve conversation(s) either select WHERE conv_id=x and/or use a GROUP BY conv_id.
Why don`t you use group by to join conversations :
select * from table where to_id = 1 group by from_id

Count how many times a value appears in sql query using php

I have created a database and website that will be used by football managers to select their team etc. Once a match has been completed events will be stored in the match_players table. Such events are Goal, Yellow Card, Red Card etc. I have no problem getting this information into php from SQL db.
I need to add up how many times a Goal appears (a '1' is placed in the SQL table) and for what team so that a final score can be displayed. So, for example, if Team A has 1 goal and Team B has 2 then I need to display that. I am trying to count the amount of times that a Goal is registered in the table. Any help will be greatly appreciated.
You can use MYSQL SUM
select SUM(Goal) from match_players where Team="A"
Or you can get the same for all teams by
select Team,SUM(Goal) from match_players group by Team
Why don't you demand this sum to SQL directly?
SELECT SUM(goals)
FROM match_table
WHERE team = 'Barcellona'
This should be much faster also than elaborate all data at "php-level"
If you want this detail for all teams
SELECT team,SUM(goals)
FROM match_table
GROUP BY team
Well if you store a 1 each time a goal is scored, your table looks like this:
TeamID goal
1 1
2 1
1 1
3 1
2 1
2 1
1 1
So you just want a count of how many times a team appears in that table:
select TeamID, count(*) from table group by TeamID
Will give you
TeamID | count(*)
1 | 3
2 | 3
3 | 1

Counting rows in a SQL query vs updating a field with PHP

I'm working in a commenting application and i would like some feedback on the method that i am using to keep track of the number of replies or likes that a comment has. Comments and replies are stored in the same table, to determine if a comment is a reply i use the field parent_id if it is anything other than 0 the comment is a reply.
Please note that i wont be including all the columns of the table below:
cid | parent_id | replies | likes
-----+-----------+---------+-------
2 | 0 | 3 | 0
3 | 2 | 0 | 0
4 | 2 | 0 | 2
5 | 2 | 0 | 0
In the table above comments with id (cid) [3,4,5] are replies of comment #2. The columns replies and likes are integer that hold the count of replies and likes accordingly. The integrity and accuracy of these columns is maintain and updated through the PHP code, for example if another reply for comment #2 is added than the replies column would be increased by one or decreased by one if deleted.
Im also aware that i could dynamically calculate the replies count in the SQL query that fetches the comments but i thought it would add more stress to the SQL server. This query would look something like these:
SELECT cid, parent_id, (
SELECT count(*)
FROM comments as SC
WHERE RC.parent_id = C.cid
) AS replies
FROM comments AS C
WHERE thread = {thread_id}
Am i doing it right by storing the replies and likes in an actual column in the table? or am i exaggerating about the stress that a query such as the one above would have in the MySql server and i should use such complex query instead?
Any feedback would be appreciated, thanks
I dont think you need the column called 'replies'. Just occupies additional unwanted space.
Do a combined Index on cid and parentId. That should be good enough. Queries should be fast.
By having the column, you are adding more stress to app code & mysql. (App code for maintaining integrity and mysql coz 2 writes in the place of 1 write - when a comment is entered).
But if you are talking about millions of rows, i wouldnt choose mysql for it, rather mongo, the data can be constructed as a beautiful JSON and dumped in mongo.

MySQL query problematic

I'm using PHP/MySQL and I have to create a new table from an existing one. Here's the problematic:
Table1:
photo_id email name_to creation_date link
1 foo1#bar.com paul 2012-11-21 link1.com
2 foo2#bar.com mark 2012-11-22 link2.com
3 foo1#bar.com alex 2012-11-23 link3.com
4 foo1#bar.com saul 2012-11-25 link4.com
5 foo1#bar.com john 2012-11-26 link5.com
6 foo2#bar.com math 2012-11-27 link6.com
7 foo3#bar.com fred 2012-11-28 link7.com
In Table1 the email is not unique, it can be repeated several times. Each link is different. With this data, I have to create a new table in which the email is unique with maximum of 3 links if there's more entries of one email (if so I need the data of the 3 latest entries).
So, in this case, Table2 would be like:
email link1 creation_date1 name_to1 link2 creation_date2 name_to2 link3 creation_date3 name_to3
foo1#bar.com link5.com 2012-11-26 john link4.com 2012-11-25 saul link3.com 2012-11-23 alex
foo2#bar.com link6.com 2012-11-27 math link2.com 2012-11-22 mark
foo3#bar.com link7.com 2012-11-28 fred
I know the GROUP_CONCAT feature but it's not really what I need here since the links would all be in the same column. Is it better to make a SELECT * FROM table1 and process the result into PHP arrays and after that create Table2 or a unique MySQL query would do the trick? Or create multiple MySQL tables?
Table1 is over 10 millions rows.
Any advice would be appreciate.
Thanks.
1) select all unique emails.
2) For each email, take the first 3 rows with that email ordered by creation_date descending.
3) Use that data to insert into new table.
Whatchu think?

Best way for saving infinit playlists (arrays) into db? (php mySql)

So client gives me a string like "1,23,23,abc,ggg,544,tf4," from user 12 . There can be infinit number of elements with no spaces just value,value,... structure. I have users table (with users uId(key), names etc). I have streams table with ( sId(key), externalID, etc values). User sends me externalId's. And I need to hawe externalId's in play list (not my sId's). I need some way to store such array into my DB and be able to get it from DB.
I need to be able to do 2 things
return such string back to user
be able to get na array from it like {1; 23; 23; abc; ggg; 544; tf4;}
So what is best method (best here means shourt(small amount of) code)
to store such data into db
to retrivew stored tata in bouth ways shown
I think, something like this should work:
User: user_id
Value: user_id, value, id
And according to your example 1,23,23,abc,ggg,544,tf4 from user 12, you will have:
TABLE User
user_id
12
and
TABLE Value
user_id | value | id
12 | 1 | 0
12 | 23 | 1
12 | 23 | 2
12 | ggg | 4
12 | abc | 3
...
id will be used for ordering list for each user, so if you want do retrieve it, just use this query: SELECT value FROM VALUE WHERE user_id = 12 ORDER BY id
That's a classical one-to-many relationship. One user has many external ids:
User: id, name
UserExternal: user_id, id # both fields as PK, id as CHAR
To fetch every external id connected to the user just execute the following query:
SELECT u.id, u.name, ue.id AS external
FROM user u
LEFT JOIN user_external ue ON u.id = ue.user_id

Categories