简体   繁体   English

如何使用子查询打印多行?

[英]How to print multiple rows using sub query?

I am new in php. 我是php新手。 I have a code in which i try to print multiple rows using sub query 我有一个代码,我尝试使用子查询打印多行

<?php
include ("connection.php");

$q_opinion="SELECT r.client_id,c.id,t.id,a.id,o.id,c.name as opinion, r.notification_date, t.title as ttitle,a.title as atitle,o.title as otitle, l.title as ltitle, s.title as stitle, pr.opinion_id, pc.id, pr.client_id as pr_client, pc.address, pc.liaison_one, city.id, pc.head_office_id, city.city, pc.title as cname
FROM og_ratings r 
LEFT JOIN og_companies c
ON r.client_id = c.id
LEFT JOIN og_rating_types t
ON r.rating_type_id = t.id
LEFT JOIN og_actions a
ON r.pacra_action = a.id
LEFT JOIN og_outlooks o
ON r.pacra_outlook = o.id
LEFT JOIN og_lterms l
ON r.pacra_lterm = l.id
LEFT JOIN og_sterms s
ON r.pacra_sterm = s.id
LEFT JOIN pacra_client_opinion_relations pr
ON pr.opinion_id = c.id
LEFT JOIN pacra_clients pc
ON pc.id = pr.client_id
LEFT JOIN city
ON city.id = pc.head_office_id
WHERE r.client_id  = (SELECT opinion_id FROM pacra_client_opinion_relations WHERE client_id = 50)
";
$result = mysql_query($q_opinion) or die;
$rating = array();
while($row = mysql_fetch_assoc($result))
{
  $rating[] = $row['cname'];
  $action[] = $row['atitle'];
  $opinion[] = $row['opinion'];
}
for ($i=0; $i<count($rating); $i++)
{ ?>
    <table border="1">
    <tr>
         <td><?= $rating[$i] ?> </td>
         <td><?= $action[$i] ?> </td>
         <td><?= $opinion[$i] ?> </td>

    </tr>
    </table>
<?php   
}
?> 

This code show me blank result in my php file. 这段代码向我显示了我的php文件中的空白结果。 But when i run this query in PhpMyadmin it show me error that it contain more than one line 但是,当我在PhpMyadmin中运行此查询时,它向我显示它包含more than one line错误

if i change my subquery with limit 如果我更改我的子查询的limit

like 喜欢

SELECT opinion_id FROM pacra_client_opinion_relations WHERE client_id = 50 LIMIT 1

Then it print record 然后打印记录

But id =50 contain 4 records. 但是id =50包含4条记录。

I want to print all record mean want to print multiple rows. 我要打印所有记录,意味着要打印多行。 How i can do it? 我该怎么办?

r.client_id = (your sub query)

When doing this, the query is trying to match the ID with one piece of data from the sub query. 这样做时,查询试图将ID与子查询中的一个数据进行匹配。 However, as you've mentioned, this query returns four pieces of data. 但是,正如您已经提到的,此查询返回四段数据。 So you want to check if the ID is IN the subquery data, not equal to it. 因此,您想检查ID是否在子查询数据中,而不是等于它。

r.client_id IN (your sub query)

The reason your query worked when you added LIMIT 1 is because your sub query was only returning one piece of data, as expected. 添加LIMIT 1时查询有效的原因是,子查询仅返回了一条数据,正如预期的那样。

Take a look here for more information on the IN clause: 在这里查看有关IN子句的更多信息:

http://www.tutorialspoint.com/mysql/mysql-in-clause.htm http://www.tutorialspoint.com/mysql/mysql-in-clause.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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