A
A
Alexander Wolf2013-09-19 23:55:00
PHP
Alexander Wolf, 2013-09-19 23:55:00

Sample from the database

Hello! I have a db table like this:

CREATE TABLE `dialogs` (
    `id` int(255) AUTO_INCREMENT,
    `to` int(255),
    `from` int(255),
    `message` text,
    `date` varchar(255),
    `read` int(1) default '0',
    PRIMARY KEY (`id`)
)

Unfortunately, I didn't design it and I can't change anything in MySQL.

For example, my table contains the following records:
+----+------+------+-----------+------------+------+
| id | to   | from | message   | date       | read |
+----+------+------+-----------+------------+------+
|  1 |    1 |    2 | Hello =)  | 1379616725 |    0 |
|  2 |    2 |    1 | World.    | 1379616743 |    1 |
|  3 |    1 |    2 | Push me)) | 1379616749 |    0 |
|  4 |    2 |    1 | World.    | 1379616743 |    1 |
|  5 |    5 |    6 | World.    | 1379616743 |    1 |
|  6 |    1 |    5 | World.    | 1379616743 |    1 |
+----+------+------+-----------+------------+------+

I need to make a selection so that I get all fields where `to`='2'. The catch is that the from field must be unique (i.e. I don't need to get all the correspondence between 1 and 2 users, but 1 of their messages is enough).
I apologize for the chaotic explanation of the problem.
After the selection, I should get something like:
+----+------+------+-----------+------------+------+
| id | to   | from | message   | date       | read |
+----+------+------+-----------+------------+------+
|  1 |    1 |    2 | Hello =)  | 1379616725 |    0 |
|  6 |    1 |    5 | World.    | 1379616743 |    1 |
+----+------+------+-----------+------------+------+

For a sample where `to`='1'

I
+----+------+------+-----------+------------+------+
| id | to   | from | message   | date       | read |
+----+------+------+-----------+------------+------+
|  2 |    2 |    1 | World.    | 1379616743 |    1 |
+----+------+------+-----------+------------+------+

For a selection, where `to`='2'

you can, of course, load everything, and then go through the loop and remove the excess, but I think this is not the most rational way :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2013-09-20
@mannaro

select * from `tablename` where `to`=1 group by from
so?

D
DenKrep, 2013-09-20
@DenKrep

select from, count(*) from dialogs where to = 1 group by from;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question