簡體   English   中英

如何顯示具有一個記錄的表記錄,而已聯接的另一個表具有許多記錄

[英]how to display table records who has one record when another table who is joined has many records

這個站點就像一個電子商務站點,我有兩個被卡住的表。

tbl_products
---------------
phash
product
price
desc
maxcount


tbl_product_images
-------------------
phash
thumb
large

tbl_products存儲產品描述tbl_product_images存儲EAC產品的拇指和大圖路徑。

phash是產品名稱的md5,是我使用的產品名稱,而不是ID或產品名稱。

我遇到的麻煩是說tbl_products有一個產品記錄,而tbl_product_images與該產品相關的圖像有5行。

我將如何運行查詢?

$sql = "select
    tbl_products.phash
    tbl_products.product
    tbl_products.price
    tbl_products.desc
    tbl_products.maxcount
    tbl_product_images.phash
    tbl_product_images.thumb
    tbl_product_images.large
    from tbl_products
    inner join tbl_product_images
    on tbl_products.phash = tbl_products_images.phash";

由於tbl_product_images有5條記錄,因此將顯示5條記錄。

我的輸出方式是我的傳統方式

$query = $db->query("$sql");
while($row = $db->fetch($query))
{
....

}

我真的不確定我將如何執行此操作,如果您需要更多我要解釋的解釋,請告訴我。 謝謝

最簡單的方法是限制來自圖像表的結果數量-盡管僅在您不關心每種產品返回哪個圖像的情況下才合適:

select
    tbl_products.phash
    tbl_products.product
    tbl_products.price
    tbl_products.desc
    tbl_products.maxcount
    tbl_product_images.phash
    tbl_product_images.thumb
    tbl_product_images.large
    from tbl_products
    inner join (SELECT * FROM tbl_product_images LIMIT 1) images
    on tbl_products.phash = images.phash

如果可以在images表中使用其他列(例如日期)來確定顯示哪個圖像,則可以向該LIMITED查詢中添加ORDER BY [col] DESC。

(注:如果在確定要返回的圖像tbl_product_images一些列,你可以要么把一個在WHERE子句的查詢,或將其包含在連接標准,如: ON tbl_products.phash = tbl_product_images.phash AND tbl_product_images.color = 'Blue'

此外,如果想獲得其所有圖像的產品,但只需要在結果一排,有可能以“轉動”圖像集成列。 但是,如果每個產品可以擁有任意數量(或僅大量)的圖像,這將非常棘手。 您最好只對每個產品返回多行,並在應用程序代碼中處理結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM