MySQL select * with distinct id - php

I am trying to select a row with a distinct id, yet return all the fields.
SELECT * DISTINCT(ID) FROM table WHERE ...
I ultimately need the ID, City, State and Zip. How can I get rows that are not duplicate ID's and return all fields into my mysql_fetch_array?
I have tried the following:
SELECT * DISTINCT(ID) FROM table WHERE ...
SELECT DISTINCT ID * FROM table WHERE ...
SELECT ID,City,State,Zip DISTINCT ID FROM ...
SELECT ID,City,State,Zip DISTINCT(ID) FROM ...
I was reading other questions here and none seem to help. Thanks in advance!

Try using GROUP BY:
select id, city, state, zip
from mytable
group by id
Note that this will return an arbitrary address for each id if there are duplicates.
Demo: http://www.sqlfiddle.com/#!2/c0eba/1

Related

Multiple PHP subqueries not giving desired result

I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.

How to select the lastest record from a group in MySQL table using SQl syntax

I'm trying to get the latest row of each group.
$SQL = "SELECT location_name, status, timecode FROM status_table WHERE location_name in ('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01') GROUP BY location_name ORDER BY status";
The query only pull up the first row, and order by timecode does not work
If you have an auto incrementing id column:
SELECT location_name, status, timecode FROM status_table WHERE id IN(
SELECT MAX(id) FROM status_table WHERE location_name in ('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01') GROUP BY location_name
) ORDER BY status
Should work by getting the MAX id for each "group" (location name) then get the details for that id, and finally order the resultset by status
It will only pull the first row because the group by is only on one column.
Try including your other selected fields in the GROUP BY clause
$SQL = "SELECT location_name, status, timecode FROM status_table
WHERE location_name in
('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01')
GROUP BY location_name, status, timecode
ORDER BY status";
I cant get you properly but till i understand i think below links really help you
1) php/MySQL insert row then get 'id'
2)Get the id of current mysql insert
3)MySQL - Select the last inserted row easiest way
4)mysql_insert_id
i hope above links are helpful....

Mysql ordering and then grouping a query in mysql

I need to order my query by date first...
So I used this:
SELECT * FROM `mfw_navnode` order by `id` DESC
I wanted to order my results from last to first.
Then what I am trying to do
is to add a query over it, which would group my results by node_name..
The result should be..all the top nodes grouped by "category/node name type", while the first node that I see is was ordered the highest for its category in the first query..
I thought to do something like this:
SELECT * FROM(
SELECT * FROM `mfw_navnode` order by `id` DESC) AS DD
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
I get no result..or any response from phpmyadmin when I input that result..
Where do I get wrong?
Note , I dont want to group my results and then order them..
I want them to be ordered, and then grouped. After being grouped..I want the result of each group to have the highest value ..from the other rows in the group
It is not sufficient to perform the ordering first, as even then MySQL makes no guarantee over which record it will select for each group. From the manual:
The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.
You must instead identify the records of interest with a subquery, then join the result with your table again in order to obtain the related values:
SELECT *
FROM mfw_navnode NATURAL JOIN (
SELECT node_name, MAX(id) AS id FROM mfw_navnode GROUP BY node_name
) AS DD
WHERE node_name IN ('Eby', 'Laa', 'MIF', 'Amaur', 'Asn')
Ordered by ID and group by node_name
SELECT * FROM `mfw_navnode`
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
ORDER BY `id` DESC
Grouping is used commonly when You are using some aggregate function (sum, max, min, count, etc). If You don't use such function in Your query then why do You want to group the results?
Anyway, this should do the trick:
SELECT *
FROM mfw_navnode
WHERE id IN (SELECT id
FROM mfw_navnode
WHERE node_name IN ('Eby', 'Laa', 'MIF', 'Amaur', 'Asn')
GROUP BY node_name)
ORDER BY id
The following SQL may yield you the required output:
SELECT node_name, MAX(id)
FROM mfw_navnode
GROUP BY node_name
ORDER BY node_name
I see two problems with your SQL.
1) placing the order by in the inline select does nothing (and is probably causing an error)
2) you are grouping on node_name but you are not aggregating anything
SELECT COUNT(id) as row_count, node_name FROM( SELECT * FROM mfw_navnode ) AS DD
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
order by node_name desc
further I am not sure why you need the inline select as the where could simply be on the original select ( perhaps you have something more complex going on that you didn't show )
SELECT COUNT(id) as row_count, node_name
from mfw_navnode
WHERE node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn'
GROUP BY node_name
order by node_name desc

sort same field from different tables

I have somes tables (around 20) with the same structure and I'm trying to sort them with a php script and insert them in a new table with the cheapest price in cheapest1, then cheapest2 for more expensive... and the most expensive in column cheapest20:
table A:
id
name
price
table B:
id
name
price
table X:
id
name
price
tableResult:
id
name
cheapest1
price1
cheapest2
price2
...
cheapestX
priceX
My code so far is:
(SELECT id, price, name FROM tableA WHERE id = $id)
UNION
(SELECT id, price, name FROM tableB WHERE id = $id)
ORDER BY price ASC
I have been looking for different solutions but it takes too long to SELECT for 15000 rows so I guess there is another way to do it.
I haven't looked for the update query yet, I need to fix the select in the first time.
Any suggestion?
EDIT: clarified question, with more tables
EDIT2: solution
I finally got it right. This is the query to select the cheapest:
I select each id and I browse:
(SELECT price AS P1, name, id FROM tableA WHERE id = ?) UNION (SELECT price AS P1, name, id FROM tableB WHERE id = ?) UNION (SELECT price AS P1, name, id FROM tableC WHERE id = ?) ORDER BY P1 ASC
Then I Insert in the new table as glglgl suggested:
('INSERT INTO table (id, name, Position, price) VALUES (?, ?, ?, ?) ');
If you have control over the final structure of the tables: Don't do that. Instead, use only one table and add a field for indicating which purpose it serves.
The target table is not structured well either. Instead, you should use
tableResult:
id
name
cheapestorder
cheapest
price
which makes all easier.
Thus, instead of having one row containing
id=10, name=foo, cheapest1=a, cheapestprice1=10, cheapest2=b, cheapestprice2=13,
you have several rows
id=10, name=foo, cheapestorder=1, cheapest=a, cheapestprice=10
id=10, name=foo, cheapestorder=2, cheapest=b, cheapestprice=13
(This process is called "normalization" in database theory.)
Putting all input tables into one simplifies dcp's query:
SELECT name,
max(mxprice) mxprice,
min(mnprice) mnprice
FROM
(
SELECT name,
max(price) mxprice,
min(price) mnprice
FROM tableABC
GROUP BY NAME, tbltag
) a
GROUP BY NAME
or maybe even just
SELECT name,
max(price) mxprice,
min(price) mnprice
FROM tableABC
GROUP BY NAME
.
I did this on Oracle, but syntax should be very similar for MySQL (the select should work without any changes at all).
CREATE TABLE tableA (NAME VARCHAR2(100), price FLOAT);
CREATE TABLE tableB (NAME VARCHAR2(100), price FLOAT);
INSERT INTO tableA VALUES ('a',14.23);
INSERT INTO tableA VALUES ('b',15.23);
INSERT INTO tableA VALUES ('b',16.23);
INSERT INTO tableB VALUES ('a',12.23);
INSERT INTO tableB VALUES ('a',13.23);
INSERT INTO tableB VALUES ('b',9.23);
SELECT name
, max(mxprice) mxprice
, min(mnprice) mnprice
FROM
(
SELECT name
, max(price) mxprice
, min(price) mnprice
FROM tableA
GROUP BY NAME
UNION ALL
SELECT name
, max(price) mxprice
, min(price) mnprice
FROM tableB
GROUP BY NAME
) a
GROUP BY NAME
Result:
NAME MXPRICE MNPRICE
1 a 14.23 12.23
2 b 16.23 9.23

How to write mysql5 query for finding duplicate rows from a table?

Hi I have a table like this
ID UserName
1 test#test.com
2 test#test.com
3 john#stack.com
4 test#test.com
5 adam#stack.com
6 john#stack.com
I need an output like this. I need only repeated rows list. How can I create this kind of an output using mysql query.
ID UserName Count
1 test#test.com 3
2 john#stack.com 2
Please help me.
Thanks.
I had the same problem some time ago and solved it like this (as far as I remember):
SELECT *
FROM tableA INNER JOIN
(SELECT DISTINCT MAX(id) as id, type_id, temp FROM tableA GROUP BY type_id, temp) AS t
ON tableA.id = t.id
AND tableA.type_id = t.type_id
AND tableA.temp = t.temp
You join the table with itself selecting the ids that are duplicate. The fields that should be tested against duplicate values are in this case type_id and temp. If you need more or less fields that should be considered as duplicates you can adjust the fields.
I don't know if this helps in your case and if it can be done in a more simple way, so I'm prepared for downvotes ;-)
Edit: removed last condition AND tableA.id < t.id as suggested by ypercube because it leads to 0 results.
It looks like you're trying to pull the following data:
First ID for a given UserName
The UserName itself
The total number of IDs for that UserName
This query should do the trick:
SELECT
MIN(id),
UserName,
COUNT(id)
FROM users
GROUP BY UserName;
since the ID is not unique so its a bit not logical to get the sum of unique UserName from the table.
If the ID is not required we can get the result from single query.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;
But in the case of ID in the result it will be a more complicated query including sub-query and inner table.
SELECT UserName
, COUNT(*) AS `Count`
FROM tableX
GROUP BY UserName
HAVING COUNT(*) > 1
Hi this is the right answer.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;

Categories