我也可以使用子查询的结果吗?

时间:2015-06-14 17:37:06

标签: php sql mysqli

我有两张桌子:

广告:字段IDABC

+----+---+-------+------+
| ID | A | B     | C    |
+----+---+-------+------+
|  1 | x | y     | z    |
|  2 | c | v     | b    |
|  3 | n | n     | m    |
+----+---+-------+------+

请求:字段IDAdIDStatus

+----+------+----------+
| ID | AdID |  Status  |
+----+------+----------+
|  3 |    1 | approved |
|  4 |    2 | pending  |
|  5 |    3 | rejected |
+----+------+----------+

ID(来自Ads)= AdID(来自Requests)。

我有查询:

SELECT * FROM Ads WHERE ID IN (SELECT AdID FROM Requests WHERE Status = 'approved' OR Status = 'rejected')

这为我提供了来自1的ID为3Ads的行。现在我的问题是,我可以使用子查询中的“已批准”或“拒绝”吗?

那么我可以说:

$sql="SELECT * FROM Ads WHERE ID IN (SELECT AdID FROM Requests WHERE Status = 'approved' OR Status = 'rejected')";
$result=mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)) {
    echo $row['Status']; //<--- doesn't work right now. Want it to say 'approved'/'rejected'
} 

它有效吗?

2 个答案:

答案 0 :(得分:1)

SELECT * FROM Ads a JOIN Requests r ON a.ID = r.AdID WHERE r.Status in ('approved', 'rejected') 查询基本上是一个过滤器。您可以使用过滤联接执行相同的操作:

where ... in

inner join过滤器不同,let text, value; if (typeof f == 'string') { text = value = f; } else { let { text, value } = f; } 过滤器包含结果中其他表格的列。

答案 1 :(得分:0)

它会给你一个错误。您只选择了广告表,其中没有“状态”列。乍一看,如果您不需要其他列,您只需查询表请求

Select /*Distinct*/ /*Adid, */ Status from Requests
 WHERE Status = 'approved' OR Status = 'rejected'

如果您还需要广告中的某些列,请进行加入

 Select a.Id, a.A,R.Status 
 from Ads a inner join Requests r on a.ID=r.AdId
 WHERE Status = 'approved' OR Status = 'rejected'