MYSQL Select on two values one column

蓝咒 提交于 2020-01-03 07:28:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!