简体   繁体   中英

How do you pull all data from a joined table when a related record contains a given value in MySQL?

I have created the following query:

SELECT wvwcs1.*, wvwcs2.* FROM wvwcs1

inner join wvwcs2 on wvwcs1.id = wvwcs2.wvwcs1_id
inner join wvwcs2 w2 on wvwcs1.id = wvwcs2.wvwcs1_id AND wvwcs2.value LIKE '%ee%'

My tables are created like so:

CREATE TABLE `wvwcs1` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `form_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 COMMENT='      ';

CREATE TABLE `wvwcs2` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `wvwcs1_id` int(10) unsigned NOT NULL,
  `value` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=latin1;

The data, as an example just using two records:

mysql> select * from wvwcs1;
+----+---------+
| id | form_id |
+----+---------+
|  1 |      23 |
|  2 |      24 |
+----+---------+
2 rows in set (0.00 sec)



mysql> select * from wvwcs2;
+----+-----------+-------+
| id | wvwcs1_id | value |
+----+-----------+-------+
|  1 |         1 | aa    |
|  2 |         1 | bb    |
|  3 |         1 | cc    |
|  4 |         2 | aa    |
|  5 |         2 | cc    |
|  6 |         2 | dd    |
|  7 |         2 | ee    |
+----+-----------+-------+
2 rows in set (0.00 sec)

What I need to do, is to select all the records from wvwcs2 where ONE of the records in wvwcs2 is a given value. So, assume that we want to select records where wvwcs2.value = dd . In this case, we would get returned:

+----+-----------+-------+
| id | wvwcs1_id | value |
+----+-----------+-------+
|  4 |         2 | aa    |
|  5 |         2 | cc    |
|  6 |         2 | dd    |
|  7 |         2 | ee    |
+----+-----------+-------+

When I run this query currently, it gives me all records. I thought I would need to do an inner join on the same table, but I must be off. I am stumped.

Try this:

SELECT A.*, C.form_id
FROM wvwcs2 A JOIN 
(SELECT DISTINCT wvwcs1_id FROM wvwcs2 WHERE LOWER(`value`) LIKE '%dd%') B
ON A.wvwcs1_id=B.wvwcs1_id
LEFT JOIN wvwcs1 C 
ON A.wvwcs1_id=C.id;

See Demo on SQL Fiddle .

Probably this is what you want here:

SELECT A.*, B.*
FROM wvwcs1 A JOIN wvwcs2 B ON A.id = B.wvwcs1_id
WHERE A.id IN
(SELECT wvwcs1_id FROM wvwcs2 WHERE value like '%ee%');

See Demo on SQL Fiddle (based on cdaigas initial work)

After the first comment the easiest solution seems to be the following (no need to join anything here at all):

SELECT * FROM wvwcs2 WHERE wvwcs1_id IN 
   (SELECT wvwcs1_id FROM wvwcs2 WHERE value like '%ee%');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM