使用>选择行1列1,但列2

时间:2015-07-23 09:08:37

标签: mysql sql mysqli

我有一个像这样的表格行:

NAME    SIZE    ARTICLE
aaa     S       1
aaa     M       1
aaa     L       1
aaa     XL      1
bbb     S       2
bbb     M       2
bbb     L       2
ccc     S       3
ccc     M       3
ccc     L       3
ddd     S       4
ddd     M       4
ddd     L       4

那些行没问题。但是让我们有另外一行:

eee     S       2
eee     XXL     2

这就是问题,因为这篇文章有ARTICLE = 2,但NAME = bbb已经使用了它。

我想选择所有ARTICLE,其中相同的ARTICLE编号与NAME(此处为bbbeee)相同,因此select将返回带有2的行数据。< / p>

我尝试了这个,但它不起作用,它将返回所有行:

SELECT NAME, ARTICLE, COUNT(NAME) FROM products GROUP BY ARTICLE, NAME HAVING COUNT(NAME) > 1

也许有一些方法可以用DISTINCT做到这一点。有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

您可以使用<button onclick="javascript:clicked_about()" type="button">About</button> <div id="homepage"> content </div> <div id="intro_page" style="display: none"> <h1 id="intro_page_caption"> About Me </h1> <div id="intro_main_text"> <p>I enjoy reading, swimming, jogging, painting and exploring.</p> </div> <div class="intro_pic1"> <figure> <img src="img/my_picture.jpg" alt="My Picture" height="250"> <figcaption>My Picture</figcaption> </figure> </div> </div>获取所需的结果,例如

exists

http://www.sqlfiddle.com/#!9/55ad8/2

答案 1 :(得分:2)

是的,你是对的,你可以使用DISTINCT

SELECT ARTICLE, COUNT(DISTINCT NAME)
          FROM products 
          GROUP BY ARTICLE 
          HAVING COUNT(DISTINCT NAME) > 1

这将返回具有多个不同名称的文章。

| article | COUNT(DISTINCT NAME) |
| 2       |  2                   |

获取与您可以使用的商品编号对应的名称 像这样的查询:

SELECT name FROM products
JOIN (SELECT ARTICLE, COUNT(DISTINCT NAME)
      FROM products 
      GROUP BY ARTICLE 
      HAVING COUNT(DISTINCT NAME) > 1) as sameArticles
ON sameArticles.ARTICLE = products.ARTICLE
GROUP BY name

输出如下:

| name|
| bbb |
| eee |