Good day.
There is a label, fields: id, ttl, str
(~ 100 records). How to ttl
, and select unique entries among them? Can all these records be written to an array?
Frankly, I do not understand why already 3 plus received a request
select `ttl` from `table` group by `ttl` order by `id`
All of you in real codes write such nonsense instead of simple DISTINCT?
2 @ Yoharny Babai - there is no need to add AS __ttl
, mysql will return an answer with fields that will be called ttl
.
And that:
$dbResult = mysql_query('SELECT DISTINCT ttl FROM table'); $ttlData = array(); // массив для заполнения значениями while($row = mysql_fetch_assoc($dbResult)) { $ttlData[] = $row; // собственно заполнение } // в данном случае получим массив вида // -> array( array('ttl'=>'...'), array('ttl'=>'...'), array('ttl'=>'...') ... ) // этот способ описан для того чтобы у вас больше не возникал вопрос о том как // сложить выборку БД в массив
If you need to get an array of the form
// array('...', '...', '...', ...);
Then
$ttlData = array(); // массив для заполнения значениями while($row = mysql_fetch_assoc($dbResult)) { $ttlData[] = $row['ttl']; // собственно заполнение } // на выход - массив значений
PS: @Shrek it's great that you know that DISTINCT performs an implicit GROUP BY, but instead of writing DISTINCT, "bullshit".
IN('','','')
is the same as id='' OR id='' OR id='' OR id=''
, why "complicate" the request (frankly, even sarcasm did not work here, because I don’t understand how such a thing could be written in the answer to such a question) that the option with group by .. order by ..
absolutely redundant - Zowie $query="select DISTINCT(ttl) FROM `table`" // первый вариант Юзайте этот (говорят он понятнее для Noob) $query="select `ttl` from `table` group by `ttl` order by `id`" // второй вариант $result=mysql_query($query);
In fact, you will choose everything, you will group them. they will be unique and then in php
while ($row=mysql_fetch_array()) { echo "Ttl=".$row['ttl']."<br />"; }
DISTINCT, as described, performs implicit GROUP BY . The difference in performance may be , but to explain it rationally difficult. It uses indices, but we need the correct composite indexes, since GROUP BY is executed after WHERE.
Request time
(7,723 total, Query took 0.0007 sec)// DISTINCT (7,723 total, Query took 0.0008 sec)// group by среднее значение примерно 0.0011 sec
SELECT DISTINCT(ttl) AS _ttl FROM `table` ORDER BY _ttl
Source: https://ru.stackoverflow.com/questions/65561/
All Articles