我有两张桌子
Products
----------------------
ProductId | ProdutName
1 | test
2 | test 2
和
SubProducts
-----------------------------------------
SubProductId | SubProductName | ProductId
1 | sub_test | 1
2 | sub_test2 | 1
3 | sub_test3 | 1
4 | sub_test4 | 2
我想从 Product 表中获取所有行,并且只从 SubProduct 中获取每个 ProductId 的第一行
结果我想要这个:
ProductId = 1
ProductName = test
SubProductId = 1
SubProductName = sub_test
ProductId = 2
ProductName = test2
SubProductId = 4
SubProductName = sub_test4
我用 if 做了这个,但我知道这是错误的,所以可以用一个查询来完成吗?
到目前为止我得到了这个:
stmt = $connection->stmt_init();
if ($stmt->prepare("
SELECT DISTINCT a.`ProductId`, a.`ProductName`, b.`SubProductId`, b.`SubProductName`
FROM `Products` as a, `SubProducts` as b
WHERE b.ProductId=a.ProductId
"))
{
$stmt->execute();
$stmt->bind_result($product_id, $product_name, $sub_product_id, $sub_product_name);
while($stmt->fetch())
{
if ($current_id!=$product_id)
{
echo 'id = '.$product_id;
echo 'thumb = '.$sub_product_name;
$current_id = $product_id;
}
}
$stmt->close();
}