简体   繁体   中英

MySQL same value once

Sorry, I speak a little English.

CREATE TABLE `links` (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
category_id INT NOT NULL, -- 1: Facebook, 2: Twitter, ...
url VARCHAR(8) NOT NULL,
state TINYINT(1) NOT NULL -- boolean
);

INSERT INTO `links` ( `id`, `category_id`, `url`, `state` ) VALUES
( 1, 1, 'cnn', 1 ), -- Facebook
( 2, 2, 'cnn', 1 ), -- Twitter
( 3, 1, 'bbc', 1 ), -- Facebook
( 4, 2, 'bbc', 1 ), -- Twitter
( 5, 1, 'cnn', 1 ), -- It's wrong. This is same as id=1
( 6, 1, 'cnn', 1 ), -- It's wrong. This is same as id=1 (and id=5)
( 7, 1, 'abc', 0 ); -- It's wrong. This is state!=1.

I would like show this after MySQL SELECT...

category_id | count
1             2
2             2

This is:

SELECT * FROM `links` ???

Thanks.

Try something like:

SELECT category_id, COUNT(DISTINCT url) AS count
FROM links
WHERE state = 1
GROUP BY category_id

You need distinct count and group by together

select 
category_id,
count(distinct url) as `count` 
from links where state = 1 group by category_id ;

To avoid inserting 5 and 6, add this to the table:

UNIQUE(`category_id`, `url`)

If you don't want to insert state=0, then do not specify it. Add DEFAULT '1' to the declaration of state and remove that column from the INSERTs.

For that matter, you may as well remove id and 1..7 from the INSERTs, since that is what AUTO_INCREMENT is all about.

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