查找具有相同多值属性的列

时间:2013-04-26 04:24:34

标签: mysql

+------------+---------------+
| BR_NAME    | FACILITIES    |
+------------+---------------+
| headoffice | fixeddeposit  |
| headoffice | locker        |
| headoffice | mobilebanking |
| headoffice | netbanking    |
| zone1      | fixeddeposit  |
| zone1      | mobilebanking |
| zone1      | netbanking    |
| zone2      | fixeddeposit  |
| zone2      | netbanking    |
| zone3      | fixeddeposit  |
| zone3      | locker        |
| zone3      | netbanking    |
| zone4      | netbanking    |
| zone5      | locker        |
| zone6      | fixeddeposit  |
| zone6      | locker        |
| zone7      | locker        |
| zone7      | mobilebanking |
| zone8      | locker        |
| zone8      | mobilebanking |
| zone9      | locker        |
+------------+---------------+

这是我的数据库我想找到具有相同多值属性的br_name ex:zone 7,zone 8如何使用mysql查询它

2 个答案:

答案 0 :(得分:2)

您可以使用group_concatalso please see fiddle

执行此类操作
CREATE TEMPORARY TABLE tt (BR_NAME VARCHAR(50),ALLFACILITIES VARCHAR(50));

INSERT INTO tt
(SELECT
    BR_NAME,
    GROUP_CONCAT(FACILITIES)
FROM
    (SELECT * FROM t ORDER BY FACILITIES) as t1
GROUP BY
    BR_NAME);

SELECT
  GROUP_CONCAT(BR_NAME) AS BR_NAMES,
  ALLFACILITIES
FROM
  tt
GROUP BY
  ALLFACILITIES
HAVING
  COUNT(*) > 1

结果:

BR_NAMES        ALLFACILITIES

zone9,zone5     locker
zone7,zone8     mobilebanking,locker

请注意,您可以移除COUNT(*) > 1并获取每个BR_NAME的设施。

答案 1 :(得分:0)

你可以使用group by和having。

SELECT * FROM TableName group by BR_NAME having count(*) >= 2

SELECT *, COUNT(*) c FROM TableName GROUP BY BR_NAME HAVING c > 1;