I have three tables as follows:
protocol
:
+----+---------+------+----------+
| id | subject | date | location |
+----+---------+------+----------+
| 1 | sub1 | c1 | s1 |
| 2 | sub2 | c1 | s2 |
| 3 | sub3 | c3 | s2 |
| 4 | sub4 | c2 | s3 |
+----+---------+------+----------+
protocol_item
:
+----+----------+-------+
| id | protocol | body |
+----+----------+-------+
| 1 | 1 | Hello |
| 2 | 2 | world |
| 3 | 2 | ok |
+----+----------+-------+
protocol_participant
:
+----------+-------------+
| protocol | participant |
+----------+-------------+
| 1 | Right 1 |
| 2 | part 72 |
| 2 | Hello 3 |
+----------+-------------+
I want to select item from the protocol_item
table where protocol_item.protocol
= 2 :
+----+---------+----------+-------+-------------+
| id | subject | location | body | participant |
+----+---------+----------+-------+-------------+
| 2 | sub2 | s2 | world | part 72 |
| 2 | sub2 | s2 | ok | Hello 3 "
+----+---------+----------+-------+-------------+
I have tried below way:
select item.id
, item.protocol
, item.body
, p.subject
, pp.participant
from protocol_item item
left join protocol p
on item.protocol = p.id
left join protocol_participant pp
on pp.protocol = item.protocol
where item.protocol = 2;
But it's showing 4 values. Where am i doing wrong? Thanks in advance.
SELECT item.id, item.protocol, item.body, p.sub, pp.participant
FROM protocol p
INNER JOIN protocol_item item ON item.protocol = p.id
INNER JOIN protocol_participant pp ON pp.protocol = item.protocol
WHERE item.protocol = 2 GROUP BY item.id
SELECT p.id as id
, p.subject
, p.location
, pi.body
, pp.participant
FROM protocol p
JOIN protocol_item pi
ON p.id = pi.protocol
JOIN protocol_participant pp
ON pi.protocol = pp.protocol
WHERE pi.protocol = 2
Am assuming the id you want in the joined table is p.id, in case you want protocol_item.id then it should be pi.id as id
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.