单个查询显示两行并假设两个表

时间:2017-05-03 08:47:37

标签: mysql

例如这是我的数据

info
----
id   name     eating                 andSaying
---  ----     ------                ---------
 1    aman     mango with sister    amanzing mango
 2    ramesh   mango via mouth      wow its really good
 3    aman     guava with jimmy     yoyo
 4    ramesh   pineapple            yummy

现在我想要一个查询,我可以获取那些具有共同eating value (table name eating)的行,例如名称为aman的ramesh和具有相同吃法的ramesh然后显示行

    info
    -----
     id   name     eating     andSaying
     ---  ----     ------     ---------
      1    aman     mango with sister    amanzing mango
      2    ramesh   mango via mouth      wow its really good

我已经尝试过此查询,但它无法正常工作

SELECT * 
FROM info a1
JOIN info a2
  ON a1.name!= a2.name
  AND a1.eating (get first array before "space"mango ) = a2.eating(get first array before "space" mango )

如果在第一个字母上吃东西,如何获得两行?

它应该像这样反映两行

  info
        -----
         id   name     eating     andSaying
         ---  ----     ------     ---------
          1    aman     mango with sister    amanzing mango
          2    ramesh   mango via mouth      wow its really good

2 个答案:

答案 0 :(得分:4)

要获取与eating个值相关的name值,您可以使用这些值:

SELECT eating
FROM info
GROUP BY eating
HAVING COUNT(DISTINCT name) > 1

输出:

eating
------
mango

将上述查询用作派生表并加入info表以获取预期结果集:

SELECT i1.*
FROM info AS i1
JOIN (
    SELECT eating
    FROM info
    GROUP BY eating
    HAVING COUNT(DISTINCT name) > 1   
) AS i2 ON i1.eating = i2.eating

修改

根据eating字段的第一个获取匹配,而不是:

GROUP BY eating

使用:

GROUP BY SUBSTRING_INDEX(`eating`, ' ', 1)

所以整个查询看起来像这样:

SELECT i1.*
FROM info AS i1
JOIN (
   SELECT SUBSTRING_INDEX(`eating`, ' ', 1) AS eating
   FROM info
   GROUP BY SUBSTRING_INDEX(`eating`, ' ', 1)
   HAVING COUNT(DISTINCT `name`) > 1
) AS i2 ON i1.eating LIKE CONCAT(i2.eating, '%');

Demo here

答案 1 :(得分:0)

我已经删除了问题中无关紧要的部分......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(name VARCHAR(12) NOT NULL
,eating VARCHAR(12) NOT NULL
,PRIMARY KEY(name,eating)
);

INSERT INTO my_table VALUES
('aman','mango'),
('ramesh','mango'),
('aman','guava'),
('ramesh','pineapple');

SELECT DISTINCT x.* 
           FROM my_table x 
           JOIN my_table y 
             ON y.name <> x.name 
            AND y.eating = x.eating;
+--------+--------+
| name   | eating |
+--------+--------+
| ramesh | mango  |
| aman   | mango  |
+--------+--------+