问题
I need to select a row from my mysql table.
In the table there are two rows with one equal value.
TABLE
-----
articleId
keywordId
Now I need to select an article, that has keyword Id = 1, as well as keyword Id = 12.
Every link to a keyword has its own record.
How can I do one select query to know, if there is an article, that matches the two keywords?
回答1:
Try this:
SELECT *
FROM tablename
WHERE keywordId IN (1, 12)
GROUP BY articleId
HAVING COUNT(*) = 2;
Check the SQL FIDDLE DEMO
回答2:
This is called Relation Division. Here is one way to do so:
SELECT *
FROM tablename
WHERE articleId IN
(
SELECT articleId
FROM tablename
WHERE KeywordId IN (1, 2)
GROUP BY articleId
HAVING COUNT(KeywordId ) = 2
);;
回答3:
You can also use subqueries for each keyword and join them
select k1.articleId from
(
select articleId from TABLE where keywordId = 1
) k1
inner join
(
select articleId from TABLE where keywordId = 12
) k2 on k1.articleId = k2.articleId
Depending on indexes and table size this can be more efficient than Group By
回答4:
SELECT *
FROM `table_name`
WHERE `keywordId` = '1' AND `keywordId` = '12'
回答5:
SELECT *
FROM table
WHERE keywordId IN (1, 12);
回答6:
select ArticleId from Table where keywordId = 1
Intersect
select ArticleId from Table where KeywordId = 12
来源:https://stackoverflow.com/questions/14196134/mysql-select-on-two-values-one-column