I have a DB like
column_1 | column_2 | column_3
------------------------------
aaa | bbb | ccc
xys | hkj | fgh
dfs | jhv | ccc
cfg | rty | fgh
iyd | olp | ccc
gdv | tdr | www
I want to get the result such that all the rows that have the same value in column_3
are printed out along with their column_3
value
column_1 | column_3
--------------------
aaa | ccc
dfs | ccc
iyd | ccc
cfg | fgh
xys | fgh
gdv | www
I know SELECT DISTINCT column_3 FROM table_name;
gives me all the unique names of column_3
but how do I get all the column_1
values that depend on column_3
?
Is it possible you're overthinking this? I believe you want
SELECT column_1,
column_3
FROM table_name
ORDER BY column_3, column_1
Select ...
From table_name As T
Where Exists (
Select 1
From table_name As T2
Where T2.column_3 = T.column_3
And T2.<Primary Key Column> <> T.<Primary Key Column>
)
Obviously, you would replace <Primary Key Column>
with the column(s) that uniquely identify each row in table_name
. If column_1
is that column, then we would get:
Select ...
From table_name As T
Where Exists (
Select 1
From table_name As T2
Where T2.column_3 = T.column_3
And T2.column_1 <> T.column_1
)
I haven't tried this in MYSQL yet, but in SQL Server this work.
CREATE TABLE table_name (column_1 CHAR(3), column_2 CHAR(3), column_3 CHAR(3))
INSERT INTO table_name VALUES
('aaa','bbb','ccc')
,('xys','hkj','fgh')
,('dfs','jhv','ccc')
,('cfg','rty','fgh')
,('iyd','olp','ccc')
,('gdv','tdr','www')
SELECT column_1
, column_3
FROM table_name a
WHERE EXISTS(SELECT column_3
FROM table_name b
GROUP BY column_3
HAVING COUNT(column_3) > 0
AND b.column_3 = a.column_3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.