简体   繁体   中英

How to fetch one of each record from table with an SQL query?

I have table containing information about a series of x number of quizzes. It includes a field for ID, Name, Subject and Level.

I would like to be able to fetch all the subjects once, so not the duplicates, because some quizzes will have the same subject.

I am then going to populate a drop down menu with this result and allow user to use it to filter their search results - if I can!

What I am stuck on is the SQL query, and I would be so grateful for any suggestions, thanks in advance!

distinct is what you want:

select distinct subject from thetable;

Add an order by if you need/want to.

如果您正在寻找没有重复值的主题

SELECT DISTINCT Subject FROM YourTable
SELECT subject FROM tbl GROUP BY subject;

在这种情况下,与DISTINCT相同。

This will bring back everything from the subject column, but without the duplicates.

SELECT DISTINCT Subject FROM myTableName

You may find that you may be better off having a separate Subject table instead of having everything in one big table.

Assuming Subject is a text field containing something like Math or English.

select distinct subject from quizzes 

Or for db's that lake distinct

select subject from quizzes group by subject

It is 'proper' however if you normalize subject/level into its own table since that information is probably repeated over and over for each quiz.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM