Get unique values of SQL table and echo with PHP - php

I have a MySQL table with over 200 values. One of the columns on my table is 'date'. Out of all 200 values there are only 5 unique dates.
How can I list out the unique values of the dates and echo them with php. e.g. not getting back 200 instances of dates but just 5.

Use DISTINCT
SELECT DISTINCT `date` FROM `tablename`....

SELECT myDate FROM myTable GROUP BY myDate
Or...
SELECT DISTINCT myDate FROM myTable
DISTINCT is a nice short hand, but if you ever then want to make use of the query for other purposes, if often constrains you a bit too much. So I prefer the GROUP BY version.

Related

Parse SQL results by month using timestamp MySQL

I have a small problem with SQL. I need to select ID of rows and group them into arrays (or something) BY MONTH? I have a timestamp column there.
So if there are rows like this:
ID Timestamp
1 blalba(1.10.2017)
2 blabla(2.10.2017)
3 blabla(1.5.1996)
The output would be like
array(
[5.1996] => array([3]),
[10.2017] => array([1,2]);
)
(Or something like this).
Is this possible in PHP using some PHP libraries? Or Do I have to implement my own class doing this?
You are probably looking for group_concat
select group_concat(id separator ', ') as myList,
DATE_FORMAT(Timestamp, '%Y-%m') from <YOUR_TABLE>
GROUP BY DATE_FORMAT(Timestamp, '%Y-%m');
Well you might be handle this on the MySQL side by ordering by month/year:
SELECT
ID, Timestamp
FROM yourTable
ORDER BY
DATE_FORMAT(Timestamp, '%Y-%m');
This query would return a result set to PHP which would be ordered such that all records in the same month and year would be clustered together. You could then just iterate this result set and process the records as you want.

MySQL select first five unique rows depending on two columns

I have a mysql table which have two columns for selecting propouses - tablica and contentid as it shows here
i want to select first five rows sorted by date DESC which have unique combination of both columns - tablica and contentid
how that can happend? I've tried already with combinations of distinct, group_concat and concat but everything i've tried skip some of the rows.
please help.
Hello_ mate
If you don't need other stuff than those two fields you can use the query I did post in the comments below your question.
Otherwise if you need all the fields you can use this query:
SELECT `id`, `tablica`, `contentid`, `ip`, `userid`, MAX(date) as `date`
FROM test2
GROUP BY tablica, contentid
ORDER BY date DESC
LIMIT 5;
using the MAX function we select the latest matching date for this tablica and contentid, if you want to get oldest date use MIN function
Let me know if this works for you.
Good Luck!

Join two tables, then Order By date, BUT combining both tables

Alright, I'm trying to figure out why I can't understand how to do this well...
I have two tables:
invoices:
id
userID
amount
date
payments:
id
userID
amount
date
So, the goal here is to join both tables, where the userID matches whatever I want it to be - and then return everything ordered by date (most recent at the top). However, because there is a date field in each of the tables, I'm not sure how MySQL will handle things... will is sort by both dates automatically? Here's what I was thinking...
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY date DESC";
But, it's starting to become clear to me that maybe this isn't even the right use of a join command... maybe I need to just get all data on each table alone, then try to sort it somehow with PHP? If that's the better method, what's a good way to do this type of DATE sort while keeping all row data in tact?
I should add, the TIME inside the unix timestamp (that's how "date" is stored) is NOT negligible - it should sort by the date and time.
Thanks all...
If the columns of both tables are the same, you can use a UNION
SELECT X.*
FROM ( SELECT `id`,
`userID`,
'INVOICE' AS PTYPE
`amount`,
`date`
FROM `invoices`
WHERE {$userID} = userID
UNION
SELECT `id`,
`userID`,
'PAYMENT' AS PTYPE
`amount`,
`date`
FROM `payments`
WHERE {$userID} = userID
) X
ORDER BY X.`date`
EDIT
Read the relevant section of the MySQL manual on UNIONS. There are other ways of phrasing this, but this is my preferred style - it should be clear to anybody reading that the ORDER BY clause applies to the result of both sides of the UNION. A carelessly written UNION - even with an ORDER BY - may still leave the final resultset in indeterminate order.
The purpose of the PTYPE is that this query returns an extra column called PTYPE, that indicates whether each individual row is an INVOICE or a PAYMENT... ie. which of the two tables it comes from. It's not mandatory, but can often be useful within a union
Because you have two identical fields named date, MySQL will not know which one you're trying to order by.
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY invoices.date, payments.date DESC";
This would sort on the invoice date, then the payment date - if that's what you are trying to find out
If your data tipe is Date, Timestamp, or anything related, the SGBD will order it properly. If that was what you've asked.
But if the datatype is String, even when dates is store, it will not sort the way you want.

MySQL Distinct (Unique) values over time

I have a question about constructing a MySQL query. I have a table with one column containing values, and another column containing timestamps. What I'd like to do is get the number of distinct (unique) values for a field from a specific epoch up until various points in time so that I can plot the number of unique values over time. For example, I'd like the query result to look like the following:
Date, COUNT( DISTINCT col1)
2011-02-01, 10
2011-02-02, 16
2011-02-03, 24
etc.
Note that these values are the number of distinct values starting the same point in time. Currently to accomplish this, I'm using a loop in PHP to iterate a single query for each date and it takes forever since I have a large DB. To give a better picture, the inefficient code I'd like to replace looks like the following:
for($i=0;$i<count($dates),$i++){
$qry = "SELECT COUNT (DISTINCT `col1`) FROM `db`.`table` WHERE `Date` BETWEEN '".$EPOCH."' AND '".$dates[$i]."';";
}
Any help would be appreciated.
Thanks
If understood your question, you can use a GROUP statement:
SELECT StampCol, COUNT(DISTINCT DataCol) FROM MyTable GROUP BY StampCol
SELECT DATE_FORMAT(date_column, "%Y-%m-%d") AS date_column, COUNT(visitors) AS visitors FROM table GROUP BY DATE_FORMAT(date_column, "%Y-%m-%d") ORDER BY date_column desc"

PHP/Mysql Columns imageid, catid, imagedate, userid

I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX

Categories