I have a table, user_quotes
, with the fields quotes_id
, quotes_user
, quotes_desc
, quotes_date
, quotes_status
, and quotes_location
. In thi开发者_C百科s quotes_user
allows duplication entries. When I execute my query I am trying to avoid duplication entries of quotes_user
. So I executed the query like this,
select distinct quotes_user from user_quotes;
This query returns only the quotes_user
field. How can I retrieve all other records using distinct quotes_user
.
I have tried with these following,
select distinct quotes_user, quotes_desc, quotes_date, quotes_status from user_quotes;
It's not avoiding the duplication of quotes_user.
If I use,
select distinct quotes_user, * from user_quotes;
I am getting mysql error,
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM user_quotes
.
How can I fetch all records using select distinct of a single column in a same table? I am storing the email address in the field. The datatype is varchar
.
Note: please don't suggest me other types like group by or other. I need to know how I can retrieve the records by only using distinct
.
In addition to what has already been said, it should be stressed that the DISTINCT
keyword can't give you distinct results for an individual column when you're selecting multiple columns. You will get distinct rows of, in your case, 4 columns. What you're observing is the expected, standard behaviour of DISTINCT
.
You say you want to retrieve the other fields, but you haven't specified how SQL is to know which values to retrieve for the other fields, for each distinct value of quotes_user
.
To show you want I mean, consider this example:
+-------------+---------------+
| quotes_user | email_address |
+-------------+---------------+
| user1 | email1 |
| user1 | email2 |
| user2 | email3 |
| user2 | email4 |
| user2 | email5 |
| user3 | email6 |
+-------------+---------------+
Now, if you just wanted quotes_user
, the output would obviously be:
+-------------+
| quotes_user |
+-------------+
| user1 |
| user2 |
| user3 |
+-------------+
But if you wanted the other fields as well, you'd need to decide whether, for example, to have email1
or email2
for the user1
row.
Perhaps what you want is to concatenate the values of the other fields together. In that case, I would suggest using the GROUP_CONCAT
aggregate function with GROUP BY quotes_user
.
I'm not sure why you want to avoid using GROUP BY
, though. Perhaps if you could explain that, we could help more.
It sounds like quotes_user
should be a foreign key like user_id
to presumably your users table. You could then query user_quotes
by user_id
returning all the quotes for that user. Your front end could then format all the quotes for each user nicely, it doesn't really sound like a MySql issue.
精彩评论